Téléchargez le texte entre guillemets [JavaScript]

  • Hacker007
  • Proficient
  • Proficient
  • Avatar de l’utilisateur
  • Inscription: Avr 07, 2004
  • Messages: 371
  • Loc: Riverside, CA
  • Status: Offline

Message Octobre 14th, 2012, 2:20 pm

Bon, il a été longtemps depuis que j'ai posté ici, mais j'ai vraiment besoin d'aide ! Je suis travaillant sur une HTA et coder beaucoup de lui à l'aide de JavaScript. Une tâche au sein de l'Application consiste à lire un fichier et prendre des paires clé/valeur et les charger dans un tableau associatif. J'ai réalisé cela, mais je veux trouver un moyen plus efficace de le faire pour accélérer le processus et maintenir le code plus propre (moins encombré). Voici mon code :

ActiveEventsLog.dbf (c'est le fichier qui est lu)
Code: [ Select ]
--------- ACTIVE EVENTS ----------

[MACH-01] = "0000001"
[MACH-02] = "0000002"
[MACH-03] = "0000003"
  1. --------- ACTIVE EVENTS ----------
  2. [MACH-01] = "0000001"
  3. [MACH-02] = "0000002"
  4. [MACH-03] = "0000003"


Voici une partie de la.Fichier HTA (la fonction JavaScript qui transforme le contenu du fichier ActiveEventsLog.dbf (ci-dessus) dans un tableau associatif (ou plutôt un objet fonctionnant comme un tableau associatif--damn JS) j'ai jeté dans des commentaires détaillés pour votre convience
Code: [ Select ]
function getActiveEvents() {

    //Just trust me, the line below loads "ActiveEventsLog.dbf" as a String
    var ActiveEventsLog = queryActiveEvents();
    
    //This object is what I return at the end..
    var ActiveEvents = new Object();
    
    //Turn the string into an array.. each new line is one array element
    ActiveEventsLog = ActiveEventsLog.split("\r\n");
    
    //Loop through each array element (each line of original file)
    for ( d = 0; d < ActiveEventsLog.length; d++ )
    {

        //If it's a Key/Value Pair line
        if ( ActiveEventsLog[d].charAt(0) == "[" )
        {
            //Next 5 Lines Rips out the [] in the "Key"
            l = "";
            l = ActiveEventsLog[d];
            l = l.split("]");
            l = l[0];
            l = l.replace("[", "");

            //Next 8 Lines Rips out the QUOTES and SPACES in the "Value"
            k = "";
            k = ActiveEventsLog[d];
            k = k.split("=");
            k = k[1];
            k = k.replace("\"", "");
            k = k.replace("\"", "");
            k = k.replace(" ", "");
            k = k.replace(" ", "");
            
            //If BOTH Key AND Value are present, add it to the return variable
            if ( ( l != "" ) & ( k != "") )
            {
                ActiveEvents[''+l+''] = k;
            }
        }
    }
    
    //Return our Associative Array(Object)
    return ActiveEvents;
}
  1. function getActiveEvents() {
  2.     //Just trust me, the line below loads "ActiveEventsLog.dbf" as a String
  3.     var ActiveEventsLog = queryActiveEvents();
  4.     
  5.     //This object is what I return at the end..
  6.     var ActiveEvents = new Object();
  7.     
  8.     //Turn the string into an array.. each new line is one array element
  9.     ActiveEventsLog = ActiveEventsLog.split("\r\n");
  10.     
  11.     //Loop through each array element (each line of original file)
  12.     for ( d = 0; d < ActiveEventsLog.length; d++ )
  13.     {
  14.         //If it's a Key/Value Pair line
  15.         if ( ActiveEventsLog[d].charAt(0) == "[" )
  16.         {
  17.             //Next 5 Lines Rips out the [] in the "Key"
  18.             l = "";
  19.             l = ActiveEventsLog[d];
  20.             l = l.split("]");
  21.             l = l[0];
  22.             l = l.replace("[", "");
  23.             //Next 8 Lines Rips out the QUOTES and SPACES in the "Value"
  24.             k = "";
  25.             k = ActiveEventsLog[d];
  26.             k = k.split("=");
  27.             k = k[1];
  28.             k = k.replace("\"", "");
  29.             k = k.replace("\"", "");
  30.             k = k.replace(" ", "");
  31.             k = k.replace(" ", "");
  32.             
  33.             //If BOTH Key AND Value are present, add it to the return variable
  34.             if ( ( l != "" ) & ( k != "") )
  35.             {
  36.                 ActiveEvents[''+l+''] = k;
  37.             }
  38.         }
  39.     }
  40.     
  41.     //Return our Associative Array(Object)
  42.     return ActiveEvents;
  43. }





Donc, comme vous pouvez le voir, j'ai utiliser 8 lignes de code pour retirer l'Id d'événement (le numéro à 7 chiffres dans les citations de ActiveEventsLog.dbf) du fichier il fonctionne, mais je pense que fonctionne mieux une regex ou quelque chose, ou peut-être un replace_all type fonction (je dois remplacer chaque citation avec valeur null individuellement dès maintenant). J'espère que quelqu'un ici (est-ce joebert encore post ici??) peut me donner une idée, que je veux mon code comme léger et efficace que possible.

Merci beaucoup !
"Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live." -Martin Golding
  • Anonymous
  • Bot
  • No Avatar
  • Inscription: 25 Feb 2008
  • Messages: ?
  • Loc: Ozzuland
  • Status: Online

Message Octobre 14th, 2012, 2:20 pm

  • ScottG
  • Proficient
  • Proficient
  • No Avatar
  • Inscription: Juil 06, 2010
  • Messages: 263
  • Status: Offline

Message Décembre 6th, 2012, 11:14 am

Vous pourriez tourner la chaîne d'information en JSON et ensuite utiliser un json decode fonction permettant de transformer un tableau (objet)

Rapidement, j'ai fait cela pour transformer votre texte exemple json
JAVASCRIPT Code: [ Select ]
function text_to_json(text) {
   
   // Turn [ and ] into "
   text = text.split('[').join('"');
   text = text.split(']').join('"');
   
   // Turn = into :
   text = text.split('=').join(':');
   
   // Break on hard space
   text = text.split("\r\n");
   
   // Join on a comma
   text = text.join(',');
   
   // Wrap in { }
   text = '{' + text + '}';
   
   // Return text
   return text;
   
}
 
// Your test info
var text = '[MACH-01] = "0000001"' + "\r\n" + '[MACH-02] = "0000002"' + "\r\n" + '[MACH-03] = "0000003"';
 
// Object like assoc array
var array_object = JSON.parse(text_to_json(text));
 
 
  1. function text_to_json(text) {
  2.    
  3.    // Turn [ and ] into "
  4.    text = text.split('[').join('"');
  5.    text = text.split(']').join('"');
  6.    
  7.    // Turn = into :
  8.    text = text.split('=').join(':');
  9.    
  10.    // Break on hard space
  11.    text = text.split("\r\n");
  12.    
  13.    // Join on a comma
  14.    text = text.join(',');
  15.    
  16.    // Wrap in { }
  17.    text = '{' + text + '}';
  18.    
  19.    // Return text
  20.    return text;
  21.    
  22. }
  23.  
  24. // Your test info
  25. var text = '[MACH-01] = "0000001"' + "\r\n" + '[MACH-02] = "0000002"' + "\r\n" + '[MACH-03] = "0000003"';
  26.  
  27. // Object like assoc array
  28. var array_object = JSON.parse(text_to_json(text));
  29.  
  30.  


La plupart des navigateurs prennent en charge JSON.parse() ; pour d'autres, vous pouvez utiliser ce script.https://github.com/douglascrockford/JSO ... r/json2.js

Afficher de l'information

  • Total des messages de ce sujet: 2 messages
  • Utilisateurs parcourant ce forum: Aucun utilisateur enregistré et 231 invités
  • Vous ne pouvez pas poster de nouveaux sujets
  • Vous ne pouvez pas répondre aux sujets
  • Vous ne pouvez pas éditer vos messages
  • Vous ne pouvez pas supprimer vos messages
  • Vous ne pouvez pas joindre des fichiers
 
 

© 2011 Unmelted, LLC. Ozzu® est une marque déposée de Unmelted, LLC