使用JSON进行数组推送

0 javascript json

有人可以告诉我为什么打印数字从117到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);
} ?
Run Code Online (Sandbox Code Playgroud)

结果:

117, 118, ..., 299, 300 
Run Code Online (Sandbox Code Playgroud)

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

Aln*_*tak 5

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

如果从循环中删除它并添加:

console.log(value);
Run Code Online (Sandbox Code Playgroud)

在最后你会看到阵列正确累积.

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

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