Reputation: 43
I am using an array to store a number of other arrays and separating each stored array by adding 'fin' at the end.
What's really throwing me is this; when I display what javascript thinks is the length of this array, it says that the array has 603 elements, whereas in reality the array contains approximately 90 elements. :-(
Code as requested:-
// 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;
I'm using 'fin' as the delimiter for each array as I have to rebuild the arrays later to save on having to do API calls to re-create most of the data.
// Example array
arrApplicationData contains
Downstream,CIM,Eserve,FPS,Global,GSAP
// Display the data in the arrForAllData
alert("arrForAllData contains " + arrForAllData );
This alert displays all the elements in the array as I expect, all comma separated.
// Calculate the length of the array
var adlen = arrForAllData.length;
alert("Number of elements in arrForAllData is " + adlen );
This alert displays 'adlen' as 603, which, as I say below is the count of all the individual characters.
For some reason the 'array.length' is counting each individual character.
Has anyone come across this before and if you have, is there a way to fix it?
Thanks in advance for your time.
Upvotes: 4
Views: 347
Reputation: 11315
We don't concatenate arrays with strings as they are casted to string. Here's what you need:
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
As an alternative to the array definition used, arrays may be instantiated by:
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'
Upvotes: 3