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
.
Maybe because keys are integer and that Javascript use keys to get the array length?
It exists a way to ignore each empty elements for length calculation?
Thank's for help!
You can use array#reduce
like below:
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. Arrays have a length
property whose value is the highest integer key present in the object + 1.
So array.length
does not return the number of elements in the array but only the value of that property.
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.