JavaScript数组长度

4

我正在使用一个数组来存储一些其他数组,并通过在末尾添加“fin”来分隔每个存储的数组。

真正困扰我的是:当我显示JavaScript认为这个数组的长度时,它表示数组有603个元素,而实际上该数组包含大约90个元素。 :-(

请求的代码如下:

//  Declare the array

var arrForAllData = new Array();

//  Concatenate all the arrays to build the 'arrForAllData' array

arrForAllData = arrApplicationData + ",fin," + arrCmdbIds + ",fin," + arrBaAvail + ",fin," + arrAppStatus + ",fin," + arrMaxAchieve + ",fin," + arrBreaches + ",fin," + arrMTTR + ",fin," + arrMTBF + ",fin," + arrMTBSI + ",fin," + arrCleanDays + ",fin," + arrHistBaAvail + ",fin," + arrHistBreaches + ",fin," + arrHistDuration;

我正在使用“fin”作为每个数组的分隔符,因为我之后需要重建这些数组,以便避免在重新创建大部分数据时进行API调用。
// Example array

arrApplicationData contains

Downstream,CIM,Eserve,FPS,Global,GSAP

// Display the data in the arrForAllData

alert("arrForAllData contains " + arrForAllData );

这个提示显示了数组中所有元素,按照我期望的方式,用逗号分隔。
// Calculate the length of the array

var adlen = arrForAllData.length;

alert("Number of elements in arrForAllData is " + adlen );

这个警告显示'adlen'为603,而下面我会解释这是所有单个字符的计数。
由于某种原因,'array.length'正在计算每个单个字符。
有人遇到过这种情况吗?如果有,有没有办法解决?
提前感谢您的时间。

11
欢迎来到 SO!请发布你的代码。 - georg
3
你是如何存储其他数组的? - Jean-Paul
4
你所做的是使用string.length获取字符串长度并获得单个字符。但是,没有代码,我无法指导你正确的方向。 - Ron van der Heijden
2
肯定的是,你没有像你想的那样使用数组。而且这个fin真的很奇怪。 - ElmoVanKielmo
3
谢谢提供代码。请尝试使用以下代码代替:var arrForAllData = []; arrForAllData.push(arrApplicationData); arrForAllData.push(arrCmdbIds );等等。请忘记那个疯狂的'fin'想法!(并阅读我发布的链接中有关数组的内容) - UpTheCreek
显示剩余13条评论
1个回答

3
我们不会将数组与字符串连接,因为它们会被转换为字符串。下面是你需要的代码:
```php implode('', $array); ```
请注意,上述代码将数组中的所有元素连接起来,并返回一个字符串。
var arrForAllData = new Array(
     arrApplicationData,
     arrCmdbIds,
     arrBaAvail,
     arrAppStatus,
     arrMaxAchieve,
     arrBreaches,
     arrMTTR,
     arrMTBF,
     arrMTBSI,
     arrCleanDays,
     arrHistBaAvail,
     arrHistBreaches
);

// And now for existing array you can always add new item
arrForAllData.push(arrHistDuration);

// You access elements of array by their index
var a = arrForAllData[5];
// 'a' is now holding the 'arrBreaches' as arrays are indexed from 0

// You can iterate over array, for example to count all the items inside nested arrays
var all_items_amount = 0;
for(var i=0; i<arrForAllData.length; i++){
    all_items_amount += arrForAllData[i].length;
}
alert(arrForAllData.length); // This will alert the length of main array
alert(all_items_amount); // This will alert the number of elements in all nested arrays

除了使用数组定义方式之外,数组还可以通过以下方式来实例化:

var x = []; // Empty array
var x = new Array(); // Empty array too
var x = [a, b, c];  // Array with three items made of variables 'a', 'b' and 'c'
var x = new Array(new object(), 'xxx', [], a);  // Array with four items:
// new instance of object, string 'xxx', new empty array and variable 'a'

你的最后一个例子有四个项目 :) - Nick
嗨ElmoVanKielmo - 感谢您提供的代码,也感谢您抽出时间来帮助我。 - steveg

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接