gpt4 book ai didi

Javascript 数组长度

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:02:52 25 4
gpt4 key购买 nike

我正在使用一个数组来存储许多其他数组,并通过在末尾添加“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'

关于Javascript 数组长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17567602/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com