Why do string indexes (although represent integers) work in arrays?

Why is the following listing correct?

var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';

arr.forEach(v => console.log(v)); // foo, bar

Both arr[1]and arr['1']are also working. Is this a sign Arraythat strings corresponding to integers are mapped to their integer value?

+4
source share
3 answers

This is because arrays in Javascript are just objects with some syntax sugar highlighted.

For comparison:

var arr = [];
arr[0] = 'foo';
arr['1'] = 'bar';
console.log(arr['0']);
console.log(arr[1]);

... to:

var obj = {};
obj[0] = 'foo';
obj['1'] = 'bar';
console.log(obj['0']);
console.log(obj[1]);

Basically, it Arrayis a type Object, with array-defined methods and non-enumerable properties, such as lengththat can be created using the selected abbreviated syntax[ items... ]

, , , ( , . ).

:

var obj = {};
obj[1.5] = 'foo';
console.log('1.5' in obj);
console.log(obj[1.5]);

var arr = [];
arr[0.5] = 'foo';
console.log('0.5' in arr);
console.log(arr[0.5]);

arr[0] = 'bar';
arr[1] = 'baz';
console.log(arr.length);
console.log(Object.keys(arr));
+2

, ,

. P ( String) , ToString (ToUint32 (P)) P ToUint32 (P) 2 ^ (32) - 1

, :

parseInt("1").toString() === "1"

"1" - .

. http://www.ecma-international.org/ecma-262/5.1/#sec-15.4

EDIT. " 1 ()", parseInt(1).toString() 1 ( "1" , ). , - "( String)", , 1 "1" , .

+1

, , , ?

. , .

- .

: var someVar = { a:1, b:2 } - 'a' : someVar['a']

Thus, it makes sense to access array elements using quoted indices.

It is not required to quote the index - and this is because, as others have pointed out, the index is forcibly cast into the string by the JavaScript engine via the implicit toString transformation

+1
source

Source: https://habr.com/ru/post/1680788/


All Articles