简体   繁体   English

如何忽略空数组元素进行长度计算

[英]How ignore empty array elements for length calculation

JS: JS:

var personnesAAjouter = [];

personnesAAjouter[idUtilisateur] = [];
personnesAAjouter[idUtilisateur]['nom'] = nomUtilisateur;
personnesAAjouter[idUtilisateur]['prenom'] = prenomUtilisateur;
personnesAAjouter[idUtilisateur]['email'] = emailUtilisateur;

For exemple, if I add an user with idUtilisateur = 102 , length of personneAAjouter is 102 .对于为例,如果我添加一个用户与idUtilisateur = 102 ,的长度personneAAjouter102

Maybe because keys are integer and that Javascript use keys to get the array length?也许是因为键是整数,而 Javascript 使用键来获取数组长度?

It exists a way to ignore each empty elements for length calculation?是否存在一种忽略每个空元素进行长度计算的方法?

Thank's for help!谢谢你的帮助!

You can use array#reduce like below:您可以像下面这样使用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);

In JavaScript arrays are object.在 JavaScript 中数组是对象。 Arrays have a length property whose value is the highest integer key present in the object + 1.数组具有length属性,其值为对象中存在的最高整数键 + 1。

So array.length does not return the number of elements in the array but only the value of that property.所以array.length不返回数组中元素的数量,而只返回该属性的值。

To actually count the number of elements in your array you could use something like this:要实际计算数组中元素的数量,您可以使用以下方法:

var arrayCount = function(myArray) {
    var count = 0;
    myArray.forEach(function(val) {
        count++;
    });
    return count;
}

I would use filter instead to keep the data type consistent (especially in typescript)我会使用过滤器来保持数据类型一致(尤其是在打字稿中)

let stringArr = [];
stringArr[3] = "abc";
const result = stringArr.filter(word => word !== undefined);

I ended up using arr.filter(x=>1).length instead of just arr.length我最终使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM