4 ms·
Actually in JS array indexing is same as property indexing right? So it's actually looking up the string '0', as in arr['0']
by krackers 10mo ago
Actually in JS array indexing is same as property indexing right? So it's actually looking up the string '0', as in arr['0']
- idle_zealot 10mo agoHuh. I always thought that JS objects supported string and number keys separately, like lua. Nope! [Documents]$ cat test.js let testArray = []; testArray[0] = "foo"; testArray["0"] = "bar"; console.log(testArray[0]); console.log(testArray["0"]); [Documents]$ jsc test.js bar bar [Documents]$
- aidenn0 10mo agoThey do, but strings that are numbers will be reinterpreted as numbers. [edit] let testArray = []; testArray[0] = "foo"; testArray["0"] = "bar"; testArray["00"] = "baz"; console.log(testArray[0]); console.log(testArray["0"]); console.log(testArray["00"]);
- minitech 10mo agoThat example only shows the opposite of what it sounds like you’re saying, although you could be getting at a few different true things. Anyway: - Every property access in JavaScript is semantically coerced to a string (or a symbol, as of ES6). All property keys are semantically either strings or symbols. - Property names that are the ToString() of a 31-bit unsigned integer are considered indexes for the purposes of the following two behaviours: - For arrays, indexes are the elements of the array. They’re the properties that can affect its `length` and are acted on by array methods. - Indexes are ordered in numeric order before other properties. Other properties are in creation order. (In some even nicher cases, property order is implementation-defined.) { let a = {}; a['1'] = 5; a['0'] = 6; Object.keys(a) } // ['0', '1'] { let a = {}; a['1'] = 5; a['00'] = 6; Object.keys(a) } // ['1', '00']
- nvlled 10mo agoLua supports even functions and objects as keys: function f1() end function f2() end local m1 = {} local m2 = {} local obj = { [f1] = 1, [f2] = 2, [m1] = 3, [m2] = 4, } print(obj[f1], obj[f2], obj[m1], obj[m2], obj[{}]) Functions as keys is handy when implementing a quick pub/sub.