JS - 使用循环填充关联数组

时间:2014-02-07 09:57:12

标签: javascript

我正在尝试使用循环填充JS数组但是不起作用 这是我的代码:

words = ["one", "two", "three", "four"];
words_formated = [];

for( var i=0 ; i<words.length ; i++ ){
    words_formated.push({words[i]: "<i>"+ words[i] +"</i>"});
}

5 个答案:

答案 0 :(得分:1)

我在尝试使用数组键直接分配对象属性名时也遇到了错误,这有效:

words = ["one", "two", "three", "four"];
words_formated = [];

for( var i=0; i<words.length; i++ ){
    var item = words[i]
    words_formated.push({item: "<i>"+ words[i] +"</i>"});
}

jsfiddle here

答案 1 :(得分:1)

当您将对象推送到数组words_formated.push({words[i]: "<i>"+ words[i] +"</i>"});时,键名words[i]不正确

如果你写

,问题就会解决

words_formated.push({words: "<i>"+ words[i] +"</i>"});

以及将word数组正确定义为words = ["one", "two", "three", "four"];

的最佳做法

答案 2 :(得分:1)

试试这个:

var words = ['one', 'two', 'three', 'four'],
    words_formated = [],
    item;
for (var i = 0; i < words.length; i++) {
    item = {};
    item[words[i]] = '<i>' + words[i] + '</i>';
    words_formated.push(item);
}

根据您自己的代码,结果将是:

[
    { one   : "<i>one</i>"   }, 
    { two   : "<i>two</i>"   }, 
    { three : "<i>three</i>" }, 
    { four  : "<i>four</i>"  }
]

数组:

var a = (1, 2, 3); // a sequence of numbers (returns the last one)
a // 3
var a = [1, 2, 3]; // an array
a // [1, 2, 3]

失败:

var k = ['name'];
var o = { k[0]: 'value' }; // SyntaxError: Unexpected token [

通行证:

var k = ['name'];
var o = {};
o[k[0]] = 'value';
o // Object {name: "value"}

答案 3 :(得分:0)

words = ("one", "two", "three", "four"); //wrong

而是在数组块中使用

words = ["one", "two", "three", "four"];

答案 4 :(得分:0)

像数组一样使用:

words = ["one", "two", "three", "four"];
var words_formated=[];

for( var i=0 ; i<words.length ; i++ ){

    words_formated[words[i]]= "<i>"+ words[i] +"</i>";
}

console.log(words_formated);