Javascript数组推送不起作用

时间:2013-09-12 15:50:25

标签: javascript arrays push

当我使用这行代码时:

for (var j = 0; j < data_ram.length; ++j) {res_ram.push([j, data_ram[j]]);}

res_cpu没有返回所有好的数据。它支持返回一个null数组(长度为30)。

这是返回的值:

Problem (Wrong values)

这是我的完整代码:

var data_cpu = [];
var data_ram = [];
var totalPoints = 30;

// random data generator for plot charts

function getRandomData() {
    if (data_cpu.length > 0 && data_ram.length > 0) {
        data_cpu = data_cpu.slice(1);
        data_ram = data_ram.slice(1);
        data_cpu.push(50);
        data_ram.push(50);
        var res_ram = [];
        var res_cpu = [];
        for (var i = 0; i < data_ram.length; ++i) res_ram.push([i, data_ram[i]])
        for (var i = 0; i < data_cpu.length; ++i) res_cpu.push([i, data_cpu[i]])

        return [res_cpu, res_ram];
    }else {
        while (data_ram.length < totalPoints) {
            data_ram.push(null);
        }
        while (data_cpu.length < totalPoints) {
            data_cpu.push(null);
        }

        var res_cpu = [];
        var res_ram = [];
        for (var i = 0; i < data_cpu.length; ++i) {res_cpu.push([i, data_cpu[i]]);}
        for (var j = 0; j < data_ram.length; ++j) {res_ram.push([j, data_ram[j]]);}
        alert(res_cpu);
        return [res_cpu,res_ram];
    }
}

2 个答案:

答案 0 :(得分:2)

res_ram.push([j, data_ram[j]]);

这将数组推送到数组,因此所有逗号。看起来j是索引,您正在寻找

res_ram[j] = data_ram[j];

res_ram.push(data_ram[j]);

如果您只想克隆阵列,为什么不

var res_ram = data_ram.slice(0);

答案 1 :(得分:2)

您的代码正常运行,但警报不是查看结果的最佳方式。请尝试使用Developer Console或Firebug。

数组中的空值在收到警报时显示为空:

alert(['a',null,'b']) // -> a,,b