3 ms·
Sorry, but that's wrong. I don't think there's any ambiguity at all. JS only has string keys, and only has objects. An array in js is just an object/dictionary
by axod 17y ago
Sorry, but that's wrong. I don't think there's any ambiguity at all. JS only has string keys, and only has objects.
An array in js is just an object/dictionary, with a special 'length' property, and a few convenience methods.
Further, the 'length' property can also be confusing to newcomers, since it doesn't relate to the number of elements in the array, rather the maximum key that can be converted to an integer +1.
For example,
var arr = [];
arr.foo = "hello";
arr[4] = 56;
// arr.length = 5
It's much easier when you understand that arrays in javascript don't really exist as a separate data type. They are, as I say, just objects with a couple of convenience methods+length property.
- s3graham 17y agoI think I agree with jrockway. I understand (now) that there's only string keys in objects, but that's the random part. Why have [] syntax for "arrays" then? It's the hashing behaviour that's the 'gotcha'. Sure, x.a should stringize 'a' to make property access work cleanly, but why when using the indexing syntax? For example: sgraham@gerard:~$ lua Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio > a = {} > a[0] = "wee" > a[1] = "waa" > a["1"] = "str" > print(a[0]) wee > print(a[1]) waa > print(a["1"]) str > > a["x"] = "wee" > a.x = "waa" > print(a["x"]) waa > print(a.x) waa > which seems wholly more reasonable.
- axod 17y ago>> Why have [] syntax for "arrays" [] syntax is for objects and arrays. As I've said, an array is just an object... Same data type. If you didn't have a [] syntax, you wouldn't be able to use a variable to reference properties on an object. var baz = "foo"; foo.bar == foo["bar"] == foo[baz]