[英]How ignore empty array elements for length calculation
JS:
var personnesAAjouter = [];
personnesAAjouter[idUtilisateur] = [];
personnesAAjouter[idUtilisateur]['nom'] = nomUtilisateur;
personnesAAjouter[idUtilisateur]['prenom'] = prenomUtilisateur;
personnesAAjouter[idUtilisateur]['email'] = emailUtilisateur;
對於為例,如果我添加一個用戶與idUtilisateur = 102
,的長度personneAAjouter
是102
。
也許是因為鍵是整數,而 Javascript 使用鍵來獲取數組長度?
是否存在一種忽略每個空元素進行長度計算的方法?
謝謝你的幫助!
您可以像下面這樣使用array#reduce
:
let arr=[]; arr[5]=1; console.log(arr.length); let myLength=arr.reduce((acc,cv)=>(cv)?acc+1:acc,0); console.log(myLength);
在 JavaScript 中數組是對象。 數組具有length
屬性,其值為對象中存在的最高整數鍵 + 1。
所以array.length
不返回數組中元素的數量,而只返回該屬性的值。
要實際計算數組中元素的數量,您可以使用以下方法:
var arrayCount = function(myArray) {
var count = 0;
myArray.forEach(function(val) {
count++;
});
return count;
}
我會使用過濾器來保持數據類型一致(尤其是在打字稿中)
let stringArr = [];
stringArr[3] = "abc";
const result = stringArr.filter(word => word !== undefined);
我最終使用arr.filter(x=>1).length
而不是arr.length
myArray = ["a","b"]
delete array[1] // deletes "b", but leaves an 'empty' slot 'existing'
console.log(myArray)
// ["a", empty]
myArray.length
// -> 2
// this is a filter that returns true for every item, but is only run for
// items that aren't empty. Note that it is non-mutating; it creates a
// new array in memory, measures its length, and then lets it disappear
// into the void.
myArray.filter(x=>1).length // -> 1
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.