以for循环语法错误创建对象

时间:2017-04-28 11:14:58

标签: javascript arrays object for-loop

我在for循环中定义对象的行的以下代码中出现语法错误。这里出了什么问题?

var NAMES     = [ 'Accessories', 'Basins' ];      
var VARIANTS  = [ ['red','green','blue'], ['red','green','blue'] ];  
var numGroups = AD_GROUP_NAMES.length;
var INFO      = [];

for (var x = 0; x =< numGroups; x++) {
    var obj = { name : NAMES[x], variants : VARIANTS[x] };
    INFO.push(obj);
}

有什么想法吗?任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:1)

将比较运算符从=<更改为>=

此外,您应将numGroups设置为长度 - 1:var numGroups = AD_GROUP_NAMES.length - 1;

&#13;
&#13;
var NAMES     = [ 'Accessories', 'Basins' ];      
var VARIANTS  = [ ['red','green','blue'], ['red','green','blue'] ];  
var numGroups = 1 ;//AD_GROUP_NAMES.length - 1;
var INFO      = [];

for (var x = 0; x <= numGroups; x++) {
    var obj = { name : NAMES[x], variants : VARIANTS[x] };
    INFO.push(obj);
}

console.log(INFO);
&#13;
&#13;
&#13;

Javascript比较运算符:https://www.ecma-international.org/ecma-262/5.1/#sec-11.8.3