arrays - JavaScript: How to create new object properties/members and assign values inside a For Loop? -
i trying create function create , assign value object property/member. i'm getting error:
uncaught typeerror: cannot read property 'id' of undefined
the function suppose create property/member called 'id', , suppose assign value newly created property/member.
var add_ids = function(array,index) { for(var iii = 1; iii <= 3; iii++) { array[index+iii].id = (array[index].id * 4)+iii; } array[index].id *= 4; };
array
array pass function.
index
position in array start on loop
p.s. loop not overwriting important. element corresponds "array[index+iii]
" empty.
array[index+iii].id = (array[index].id * 4)+iii;
in that, if array[index+iii]
undefined
before, array[index+iii].id
give error you've mentioned.
so before accessing id
check whether property exists.
if(!array[index+iii]) array[index+iii] = {}; // initializing if not present. array[index+iii].id = (array[index].id * 4)+iii;
Comments
Post a Comment