Consider the following:
var answers = []; answers[71] = { field: 'value' }; answers[31] = { field: 'value' }; console.log(answers);
This displays the length of the array as 72 , but I expected it to return 2 . Here's the script output from the chrome console:
Any ideas why this is?
You can calculate the actual number of keys with Object.keys(arr).length:
Object.keys(arr).length
const answers = []; answers[71] = { field: 'value' }; answers[31] = { field: 'value' }; console.log(Object.keys(answers).length); // prints 2
By defining index 71, you told the array that it should contain at least 72 entries, and any that you do not explicitly define will contain a value undefined.
undefined
, , undefined , , undefined
Array#forEach Array#reduce
Array#forEach
Array#reduce
var answers = [], count = 0; answers[71] = { field: 'value' }; answers[31] = { field: 'value' }; answers.forEach(_ => count++); console.log(count); console.log(answers.reduce(r => r + 1, 0));
Object.keys(your_object_like_array).length
.
Array#filter , undefined.
Array#filter
answers.filter(function(v){ return true; }).length
var answers = []; answers[71] = { field: 'value' }; answers[31] = { field: 'value' }; console.log(answers.filter(function(v) { return true; }).length);
, ?
MDN:
length 32- , .
length
spec:
, , , , length , , , ;
, , . ,
answers[71] = {field: 'value'}; answers[31] = {field: 'value'};
72,
delete answers[71];
72, - 32.
, , . , , , , in:
in
let count = 0; for (let i = 0; i < arr.length; i++) count += i in arr;
Source: https://habr.com/ru/post/1654049/More articles:CSS for the accordion menu for mobile devices - cssCustom getter for type parameter properties - kotlinКак проверить методы и обратный вызов с помощью Mocha, Chai и Enzyme в React-Redux - reactjsAVG antivirus detects my React Native Android app as malware - androidAre static data members safe as C ++ default arguments? - c ++How to use interactive with a box containing widgets? - ipywidgetsZF3 redirection after ACL authorization - phpDjango BooleanField as a drop down list - pythonUnderstanding how scroll animation works - javascriptHow does asyncio.sleep work with negative values? - pythonAll Articles