我正在使用一个数组来存储许多其他数组,并通过在末尾添加'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'正在计算每个字符。
有没有人遇到过这个问题,如果有的话,是否有办法解决这个问题?
提前感谢您的时间。
答案 0 :(得分: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'