我为句子中的索引空间创建了一个关联数组,例如:
句子:你好,你好吗? ('你好'到'怎么'这个词之间的空格)所以我的数组看起来像这样:
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将其视为一个字符串,会将数字键置于其上方。
答案 1 :(得分:0)
您不能在javascript中为数组使用非数字索引(a_b不被视为数字)。为此你可能应该使用一个对象。然后循环遍历它:
rvm