与JS数组长度斗争

时间:2012-03-19 12:53:38

标签: javascript arrays

我有这段代码,当你看到它时,似乎逻辑运行如下:

我创建了3个空数组,我向bankSelectedData添加了一个值,我打印出了值,显然bankSelectedData现在为1而bankSelectionArrayCurrent长度为0,但后来我说:

bankSelectionArrayPrevious = bankSelectionArrayCurrent;

所以我将bankSelectionArrayPrevious转换为bankSelectionArrayCurrent。当我检查bankSelectionArrayPrevious的大小是'1'时?这怎么可能?

var bankSelectionArrayCurrent = new Array();
var bankSelectionArrayPrevious = new Array();
var bankSelectedData = new Array();
    bankSelectedData.push("value1");

alert("bankSelectionArrayCurrent length: "+bankSelectionArrayCurrent.length);
alert("bankSelectedData length: "+bankSelectedData.length);

if(bankSelectedData.length != bankSelectionArrayCurrent.length){
    bankSelectionArrayPrevious = bankSelectionArrayCurrent;
    bankSelectionArrayCurrent.length = 0

    alert("previousSize: "+bankSelectedData.length);
    alert("currentSize: "+bankSelectionArrayCurrent.length);
}​

感谢您的任何建议!

3 个答案:

答案 0 :(得分:2)

您的代码永远不会更改“bankSelectedData”,因此在您添加第一个值后,其长度将保持为1。

您的代码不包含任何长度为“bankSelectionArrayPrevious”的alert()来电。

答案 1 :(得分:2)

您的提醒错误。它应该是:

alert("previousSize: "+bankSelectionArrayPrevious.length);

答案 2 :(得分:2)

你在哪里

alert("previousSize: "+bankSelectedData.length);

也许你的意思是:

alert("previousSize: "+bankSelectionArrayPrevious.length);