This question already has answers here:
Why does 2 == [2] in JavaScript?
(9 answers)
Closed 6 years ago.
I'm failing to find documentation as to how/why the following works:
const data = {one: 1, two: 2}
const key = ['one']
data[key[0]] // 1
data[key] // 1
data[[key]] // 1
data[[[key]]] // 1
data[[[[key]]]] // 1
data[['one', 'two']] // undefined
What allows any number of square brackets to surround the key and still successfully find the key in the object? Is there specific behavior when array.length === 1? And if so, where can I find documentation or clarity on that?
When using the object[key] bracket notation to access properties, the key is converted to a string.* The string representation of an array is the string representations of its elements joined with ,. For a one-element array, that's the same as the string representation of its only element.
const foo = {'a,b': 2};
console.log(foo[['a', 'b']]); // 2;
* Or a symbol.
When you access a property using square brackets, the key is always converted to string. And if you convert an array to string, the result is the same as calling the join() method on the array. Therefore, converting to string an array, which contains only one element, which is a string results in that element itself. However, when array contains two string elements (like ['one', 'two']), converting it to string results in 'one,two', and the data variable doesn't contain that key.
Related
This question already has answers here:
What do square brackets around a property name in an object literal mean?
(2 answers)
Closed 2 years ago.
Currently, we're calling a 3rd party service with the following JavaScript object:
props = { ['356']: false, ['456']: true}
I notice that when I enter it into the Chrome browser console and re-inspect the object I get the following output:
props = { 356: false, 456: true}
What is going on here? Is '356' still a string after apparently being automatically casted from an object key that is an array of one string? It looks like it automatically got converted to an integer.
['356'] when used as an object key is not an array, it's using computed properties, hence the conversion to the string '356'. Object keys are strings. You can test this with other types, for example in {[function(){}]: 1} they key is the string 'function(){}'. If for whatever reason you need an array representation, you can call JSON.stringify, though that will give you back a JSON string with an array, not an array itself:
const foo = { [JSON.stringify(['foo'])]: 1}
// "[\"foo\"]": 1
Keys in object is always string. Next syntax isn't about array:
props = { ['356']: false, ['456']: true}
Values in [...] is calculated in runtime, so:
props = { [5 + 6]: false, ['a' + 'b']: true}
is the same as:
props = { '11': false, 'ab': true}
This question already has answers here:
Why is 0[0] syntactically valid?
(7 answers)
Closed 6 years ago.
Is the number 1 cast to an empty array implicitly?
> a = 1[1]
undefined
> console.log(a)
undefined
undefined
Is the number 1 cast to an empty array implicitly?
No. The number value is implicitly (and temporarily) converted to a number object and the property 1 is accessed on that object.
The bracket notation you are using ([1]) is not specific to arrays, every object property can be accessed via bracket notation. I.e. the following two are equivalent: obj.foo (dot notation) and obj['foo'] (bracket notation).
Number objects however don't have a property 1 and accessing a non-existing property returns undefined:
var numObj = new Number(1);
console.log(numObj[1]);
The implicit conversion happens every time you access a property on a primitive value, whether the property exists or not. In the following example, the primitive number value is also implicitly converted to an object and then its toFixed method is executed:
var num = 42;
console.log(num.toFixed(2));
// or equivalently to your example:
console.log(42['toFixed'](2))
Numbers, Strings, Booleans and Symbols have object equivalents. Null and Undefined don't.
This question already has answers here:
Length of a JavaScript associative array
(4 answers)
Closed 6 years ago.
I read that array can be as map, so why does it gives wrong result?
Is there simple native way to use map in JavaScript and then get the length of it?
var f = [];
f["1_f_1"] = "1";
f["2_f_2"] = "2";
f["3_f_3"] = "3";
alert(f.length);
prints : 0
https://jsfiddle.net/fd6s1z0j/
JavaScript is not supported associative array so use object and get size by property name array size with the help of Object.keys() method.
// initialize as object
var f = {};
// define properties
f["1_f_1"] = "1";
f["2_f_2"] = "2";
f["3_f_3"] = "3";
// get object property name array and get length
alert(Object.keys(f).length);
An Array in JavaScript is just a special kind of an Object. If the keys of the Array object is a valid Array index (positive integer), only then it will be considered as an array element. Quoting the specification,
An integer index is a String-valued property key that is a canonical numeric String (see 7.1.16) and whose numeric value is either +0 or a positive integer ≤ 253−1. An array index is an integer index whose numeric value i is in the range +0 ≤ i < 232−1.
In your case, you are creating three new properties which are not valid array indexes. That is why they are not considered as the array elements, but just properties of the array object.
If you want to store those strings, then you should store them in an Object, like shown in the other answer.
There are no associative arrays in JavaScript. Although, there are objects with named properties. What is often referred to as "associative array" is actually just an object in Javascript. If you want to get the length of element, you need to count all enumerable properties found directly upon object or simply use:-
Object.keys(obj).length
This question already has answers here:
Why does javascript turn array indexes into strings when iterating?
(6 answers)
Is a JavaScript array index a string or an integer?
(5 answers)
Why is key a string in for ... in
(3 answers)
When iterating over values, why does typeof(value) return "string" when value is a number? JavaScript
(1 answer)
Closed 1 year ago.
I noticed that in Javascript a variable used as the index in a for..in loop will be always a string even if I define it the following way:
var s_array = new Array();
s_array[0] = 'foo';
s_array[1] = 'bar';
for(i in s_array){
alert(typeof(i)); // String
}
Why is it considered a string and not a number?
The for(x in y) syntax is intended to iterate over the properties of an object (not the indexes of an array), and property names are always stored as strings.
The fact that it also works for arrays is a side effect of array elements being properties on the array object.
To understand the difference, consider this code:
var s_array = new Array();
s_array[0] = 'foo';
s_array[1] = 'bar';
s_array['foo'] = 'bar';
console.log("Object:");
for(i in s_array) {
console.log(i);
}
console.log("Array:");
for(var i = 0, l = s_array.length; i < l; i++) {
console.log(i);
}
which provides the following output:
Object:
0
1
foo
Array:
0
1
There's a foo property on the object, but it's not actually an element inside the array.
Arrays are essentially objects with managed set of indexed keys.
Since every key in an object is of type string hence it is a string as well.
Consider your array as :
{"0" : "foo" , "1" : "bar"}
So your
for(i in s_array){ alert(typeof(i)); }
can be read as
for each key in the s_array
In js arrays are high-level, list-like objects (associative arrays).
indexes eventually gets coerced into a string by the JavaScript engine, anyway, through an implicit toString conversion.
source: MDN
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
javascript array associative AND indexed?
I am returning an array from a function and am wondering if I can have both a string association and numerical associations as well.
Ex:
array[0] = green;
array[1] = blue;
array['what'] = colors;
In some way yes, because it's some type of Object. But it's wrong use of them :)
Use objects ({}) for named (stringish) indexes and arrays([]) for number indexes.
Arrays are just objects with a special length property and some handy inhertited methods. Since arrays are objects, their property names are strings however the numeric ones ('0','1','2', etc.) are visited by array methods whereas non–numeric ones (e.g. length) aren't. Also, many array methods are generic and can be applied to any object with suitable properties (i.e. a numeric length property and some numeric property names).
Note that to be considered an index, the property name must satisfy the rules for index names so:
var x = [];
x['00'] = '00'; // length = zero as '00' is not an index
x['0'] = '0'; // length = 1 as '0' is an index
It's generally considered bad form to use an array where a plain object will do, though there are no consequences for doing so other than if you mess with the length property.