使用JSON进行数组推送 [英] array push with JSON

查看:91
本文介绍了使用JSON进行数组推送的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以告诉我为什么打印117至300的数字吗?

Can some one tell me why this prints numbers from 117 to 300?

var x = [12, 55, 177];
var y = [25, 75, 255];
var value = [];

for (var i = 1; i <= 300; i++) {
    value.push(JSON.stringify(i));
    document.write(value);
} ​

结果:

117, 118, ..., 299, 300 

(jsFiddle http://jsfiddle.net/minagabriel/6crZW/)

(jsFiddle http://jsfiddle.net/minagabriel/6crZW/)

推荐答案

之所以这样做,是因为document.write()是一个古老的讨厌的黑客,不应该使用,并且与jsfiddle不兼容.

It does that because document.write() is an old nasty hack that shouldn't be used, and isn't compatible with jsfiddle.

如果您将其从循环中删除并添加:

If you remove that from the loop and add:

console.log(value);

最后,您会看到数组已正确堆积.

at the very end you'll see that the array is correctly accumulated.

此外,您可能只想对构建后的数组 进行JSON编码:

Furthermore, you probably only want to JSON encode the array after it's built:

var value = [];
for (var i = 1; i <= 300; i++) {
    value.push(i);
} 
console.log(JSON.stringify(value));

这篇关于使用JSON进行数组推送的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆