Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

First element in object is undefined using += operator

I have a problem to use the operator += in an object. Because i have to change the variable dynamically i use an object as variable. But if i use the += operator the first element in the output always gets undefined. I think thats because the object is initialized empty.

What is the best solution to prevent to output that element ?

Here goes my example code:

var dynamicVariable = {};
var group = "apples";

for(var i = 1; i<5; i++)
{
 dynamicVariable[group] += " Apple" + i + "<br>";
}

document.getElementById("fruits").innerHTML = dynamicVariable[group];

jsFiddle

like image 390
selman Avatar asked Feb 10 '23 14:02

selman


1 Answers

This is happening because dynamicVariable[group] has the value undefined before you start appending to it. undefined + " Apple1" is "undefined Apple1".

You need to initialize it to an empty string first:

dynamicVariable[group] = "";
for(var i = 1; i<5; i++) {
    dynamicVariable[group] += " Apple" + i + "<br>";
}
like image 192
JLRishe Avatar answered Feb 13 '23 05:02

JLRishe