I'm trying to fill an JS array using a loop but is not working This is my code:
words = ["one", "two", "three", "four"];
words_formated = [];
for( var i=0 ; i<words.length ; i++ ){
words_formated.push({words[i]: "<i>"+ words[i] +"</i>"});
}
I also got an error with trying to use the array key to directly assign the object property name, this worked:
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
As your are pushing an object into array words_formated.push({words[i]: "<i>"+ words[i] +"</i>"}); , the key name words[i] is not correct
The problem will get solved if you write
words_formated.push({words: "<i>"+ words[i] +"</i>"});
and its best practice if you define word array correctly as words = ["one", "two", "three", "four"];
Try this :
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);
}
According to your own code, the result will be :
[
{ one : "<i>one</i>" },
{ two : "<i>two</i>" },
{ three : "<i>three</i>" },
{ four : "<i>four</i>" }
]
Array :
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]
Fails :
var k = ['name'];
var o = { k[0]: 'value' }; // SyntaxError: Unexpected token [
Passes :
var k = ['name'];
var o = {};
o[k[0]] = 'value';
o // Object {name: "value"}
codevar item = words[i] words_formated.push({item: "<i>"+ words[i] +"</i>"})code[{one:'<i>one</i>'}]Use like an array:
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);
alert(JSON.stringify(words_formated)); unless we declare words_formated as an object - var words_formated={}; Thank you
[...]