使用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));