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”正在计算每个单独的字符。

以前有没有人遇到过这个问题,如果有,有没有办法解决它?

在此先感谢您的时间。

4

1 回答 1

3

我们不会将数组与字符串连接起来,因为它们被转换为字符串。这是您需要的:

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'
于 2013-07-10T12:06:19.367 回答