簡體   English   中英

Javascript數組長度

[英]Javascript array length

我使用一個數組來存儲許多其他數組,並通過在末尾添加'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'計算每個單獨的字符。

有沒有人遇到過這個問題,如果你有,有沒有辦法解決它?

在此先感謝您的時間。

我們不會將數組與字符串連接起來,因為它們被轉換為字符串。 這就是你需要的:

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'

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM