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
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
Share Improve this question asked Mar 22, 2015 at 19:10 selmanselman 1681 silver badge8 bronze badges 1-
3
Just first set
dynamicVariable[group] = ""
– Farzher Commented Mar 22, 2015 at 19:14
1 Answer
Reset to default 8This 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>";
}