Array as map returns wrong length [duplicate] - javascript

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

Related

Why can we use the .length property in string types? [duplicate]

This question already has answers here:
How does primitive types in Javascript have methods and Properties? [duplicate]
(2 answers)
Closed last year.
Hello I'm new to JS and object-oriented programming in general.
I have two questions considering this
let arr = [1,2,3]
let a = 'hi'
When I run typeof(), arr is 'object' and a is 'string' right?
So my question is ,
When using arr.length to get the length of the array, what's the principle behind it? To be specific, I don't understand how I could get the length property though I've never initialized it. Does JS automatically set a length property value when we generate an object? How does it work?
Doesn't property only exist in objects? But why can we get the length of variable a using a.length? I thought objectname.property thing was for objects.
When you declare [1,2,...] you are declaring an object of class Array, which, in it's prototype, has a "length" property. Think of it as a variable that gets updated when you add or remove elements from the array.
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Array/length
Strings are also objects in Javascript, and a string is also considered an array of characters, thus having the "length" property as well.
https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/String

Why does the console displays typeof as object for an array? [duplicate]

This question already has answers here:
Why does typeof array with objects return "object" and not "array"? [duplicate]
(3 answers)
Closed 5 years ago.
var array = new Array("sfsdf", "sdvgsdfswde");
console.log(typeof array);
Well because in Javascript an Array IS an object. Check the docs here
The JavaScript Array object is a global object that is used in the
construction of arrays; which are high-level, list-like objects
Arrays are list-like objects whose prototype has methods to perform
traversal and mutation operations. Neither the length of a JavaScript
array nor the types of its elements are fixed. Since an array's length
can change at any time, and data can be stored at non-contiguous
locations in the array, JavaScript arrays are not guaranteed to be
dense; this depends on how the programmer chooses to use them. In
general, these are convenient characteristics; but if these features
are not desirable for your particular use, you might consider using
typed arrays.
var a = []
typeof a
==> "object"
because Array is inherited from an type of object.if you want to check its an Array or not then use this method
Array.isArray(a) ==> true

JavaScript property accessors wrapped in array [duplicate]

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.

Why does the typeof a numerical array index in a "for..in" loop considered a string? [duplicate]

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

Can a javascript array be both numerical and associative? [duplicate]

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.

Categories

Resources