简体   繁体   中英

Javascript array push doesn't work

when I use this line of code:

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

res_cpu doesn't return at all the good data. It's supports to return a array of null (of length 30).

Here is the returned value:

问题(值错误)

Here is my full code:

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];
    }
}
res_ram.push([j, data_ram[j]]);

This pushes an array onto an array, hence all the commas. It looks like j is the index and you were looking for

res_ram[j] = data_ram[j];

or

res_ram.push(data_ram[j]);

If you just wanted to clone the array, why not

var res_ram = data_ram.slice(0);

?

Your code works properly, but the alert isn't the best way to view the results. Try Developer Console, or Firebug instead.

Null values in arrays show up as empty when alerted:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM