2016-11-20 4 views
0

を混ぜ、私は例えば、文の内部索引スペースのための連想配列を作成しました:各&ループのための私の配列順序

文:こんにちは         どのようにあなたは? 、

indexed_words[0] = hello 
indexed_words[0_1] = space 
indexed_words[0_2] = space 
indexed_words[0_3] = space 
indexed_words[0_4] = space 
indexed_words[0_5] = space 
indexed_words[0_6] = space 
indexed_words[0_7] = space 
indexed_words[1] = how 
indexed_words[2] = are 
indexed_words[3] = you? 

が、私は「for」ループを使用する場合、そのインデックス0(アラートを使用して)私を示しています(「どのように」と単語の間のスペース「ハロー」)

はので、私の配列は次のようになります1,2,3最初とその後、サブインデックス、それは私の配列の順序、任意のアイデアを混在?

ここに私のコード:

function words_indexer(user_content) 
{ 

     var words_array = user_content.split(" "); 

     var indexed_words = {}; 

     var word_counter = 0 

     var last_word_counter = 0 

     $.each(user_content, function(word_key,word_value){ 


      if(word_value === ''){ 

       var indexed_key = last_word_counter + '_' + word_key; 

       indexed_words[indexed_key] = word_value; 


      }else{    

       var indexed_key = word_counter; 

       indexed_words[indexed_key] = word_value; 

       last_word_counter = word_counter; 

       word_counter++;    
      } 

     }); 


     for (var key in indexed_words) { 
      alert(key + ' ' + indexed_words[key]); 
     }  
} 
+0

達成したいことを追加してください。 –

答えて

2

あなたの配列インデックスは、構造体の余分なレベルを必要とする場合、だけではなく、ネストされた配列を作成した方がよい場合があります。

indexed_words[0] = hello 
indexed_words[0][1] = space 
indexed_words[0][2] = space 
indexed_words[0][3] = space 
indexed_words[0][4] = space 
indexed_words[0][5] = space 
indexed_words[0][6] = space 
indexed_words[0][7] = space 
indexed_words[1] = how 
indexed_words[2] = are 
indexed_words[3] = you? 

を私はアンダースコアを追加すると信じてあなたの配列のキーに実際には、Javascriptがあなたの上にあなたの数字キーをバンプする文字列としてそれを考えることがあります。

0

javascriptの配列に数値以外のインデックスを使用することはできません(a_bは数値と見なされません)。このためにはおそらくオブジェクトを使うべきです。そして、次のようにループしてください:

for(var word_key in indexed_words) { 
    if(!indexed_words.hasOwnProperty(word_key)) continue; 
    var word_value = indexed_words[word_key]; 
    // Your code 
}