简体   繁体   中英

Javascript - array index issue in non sparse array

non sparse array are contiguous in nature and from 0 to length-1, all index should return true for 'in' operator. It should be true also for empty element.

obj1 = {x:1,y:2};
obj2 = Object.create(obj1);
obj2.z = 5;
var arr = [obj1,obj2,1,,2];

console.log(arr.length); //5
console.log(3 in arr);//false

index 3 is valid. Why is it returning false?

Note: I am using latest firefox.

It should return false only for sparse array which doesn't have a specified index number 3.

Update: index 3 is valid so it should return true. in operator doesn't validate value of at the indexed position, it just validate the validity of index not the value

3 in arr is false because arr[3] is never set (and thus the array is indeed sparse).

Note the double comma in

var arr = [obj1,obj2,1,,2];

– if you make that

var arr = [obj1,obj2,1,2];

then 3 in arr becomes true .

See page 63 in the specification :

Array elements may be elided at the beginning, middle or end of the element list. Whenever a comma in the element list is not preceded by an AssignmentExpression (ie, a comma at the beginning or after another comma), the missing array element contributes to the length of the Array and increases the index of subsequent elements. Elided array elements are not defined. If an element is elided at the end of an array, that element does not contribute to the length of the Array.

– in other words, the behavior of your code is identical to

var arr = [obj1, obj2, 1];
arr[4] = 2;

Javascript is evaluating the value which is undefined. Undefined is falsy.

Array always have 0 based index, in your array 4th element (3 by index) is not set to any value.

Refere this

From the link

Here is what is falsy in JavaScript:

  • false
  • null
  • undefined
  • The empty string
  • ''
  • The number 0 The number NaN (yep, 'Not a Number' is a number, it is a special number)

Everything else is truthy, and that includes Infinity (which is another special number, like NaN), and all Object objects and Array objects, empty or not.

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.

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