最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - First element in object is undefined using += operator - Stack Overflow

programmeradmin2浏览0评论

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
Add a ment  | 

1 Answer 1

Reset to default 8

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>";
}
发布评论

评论列表(0)

  1. 暂无评论