我有一个学习javascript的简单问题。
我用这样的对象创建一个数组
var myresult =new Array(); [];
for (i= 2015;i<=2030;i=i+1)
{
var newobject={'myname' : i};
myresult.push(newobject);
}
console.log ('Result:'+myresult);
console.log(JSON.stringify(myresult));
在控制台中,我看到此输出
Result:[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
[{"myname":2015},{"myname":2016},{"myname":2017},{"myname":2018},{"myname":2019},{"myname":2020},{"myname":2021},{"myname":2022},{"myname":2023},{"myname":2024},{"myname":2025},{"myname":2026},{"myname":2027},{"myname":2028},{"myname":2029},{"myname":2I30}]
答案 0 :(得分:1)
您使用了字符串串联,该字符串将对象字符串化为JSON。使用
console.log('Result:', myresult);
相反。
编辑:我刚刚在Firefox Javascript控制台中尝试过此操作:
>> const myresult = [];
undefined
>> const newobject = {'myname': 1};
undefined
>> console.log('NEWOBJECT:', newobject);
NEWOBJECT: Object { myname: 1 }
debugger eval code:1:1
undefined
>> myresult.push(newobject);
1
>> console.log('MYRESULT:', myresult);
MYRESULT: Array [ {…} ]
debugger eval code:1:1
undefined
即记录对象工作正常。