0

我不确定问题出在哪里,但这是我的代码

var btotal = [];
var songarray = [];
function whileplaying() {
    var playingSound = soundManager.getSoundById('aSound');
    for (var i=0;i<8;i++) {
        var ttotal = 0;
        for (var n=0;n<32;n++) {
            var eblock = (i*32)+n;
            ttotal = ttotal+(playingSound.eqData.left[eblock]*100);
        }
        ttotal = ttotal/32;
        btotal[i] = ttotal;
    }
    console.log(btotal);
    songarray.push(btotal);
}

解释一下,在播放声音时,我得到一个长度为 8 的数组,将那个频率块的 EQ 值相加。最后,我将此数组附加到 songarray,因此理论上是 songarray 是一个数组,其中包含数组中的声音 EQ 数据。

问题是,当我获得 songarray 的值时,其中有许多我期望的数组,但它们都是相同的,并且都是最后一个数据点的值,即 btotal 的最新值。

所以这段代码会运行,控制台会显示(例如):

[42.743750000000006, 2.98125, 0.10625000000000001, 0, 0, 0, 0, 0]
[38.859374999999986, 2.8, 0.09375, 0, 0, 0, 0, 0]
[56.26874999999998, 21.831250000000004, 3.853125, 0.340625, 0, 0, 0, 0]
[46.459374999999994, 19.584374999999998, 1.4, 0, 0, 0, 0, 0]
[38.08125, 11.8, 1.0750000000000002, 0, 0, 0, 0, 0] 

然而歌曲数组的内容是这样的:

0: Array[8]
0: 38.08125
1: 11.8
2: 1.0750000000000002
3: 0
4: 0
5: 0
6: 0
7: 0
length: 8
__proto__: Array[0]
1: Array[8]
0: 38.08125
1: 11.8
2: 1.0750000000000002
3: 0
4: 0
5: 0
6: 0
7: 0
length: 8
__proto__: Array[0]

其中是最新的 btotal 数组的所有内容。这使我相信 songarray 中的每个条目仅指向 btotal。那么我如何才能使 songarray 中的每个数组在我附加它时都是 btotal 的值,而不仅仅是一个指针?

4

2 回答 2

1

您可能想要复制数组。

代替

songarray.push(btotal);

利用

songarray.push(btotal.slice(0));
于 2012-12-07T00:30:32.230 回答
1

btotal在函数范围内定义:

var songarray = [];
function whileplaying() {
    var btotal = [];
    var playingSound = soundManager.getSoundById('aSound');
    for (var i=0;i<8;i++) {
        var ttotal = 0;
        for (var n=0;n<32;n++) {
            var eblock = (i*32)+n;
            ttotal = ttotal+(playingSound.eqData.left[eblock]*100);
        }
        ttotal = ttotal/32;
        btotal[i] = ttotal;
    }
    console.log(btotal);
    songarray.push(btotal);
}
于 2012-12-07T00:30:48.060 回答