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.
Related
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
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:
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
Closed 8 years ago.
What is the correct way on instantiate empty array in javascript?
var array=new Array();
var array=new Array;
var array=[];
All of them look same. Is there any difference?
var array=[];
works best.
Ref - http://jsperf.com/array-instantiation
There is one more way:
var array = Array() ;
They all will produce the same result, an empty object Array. I think the best way is using the array literal shortcut [] as it is what use less characters, it is what most people do.
Note that the same does not apply in the case of Boolean, Number and String, as those constructors will return primitives of type 'object' (object Boolean, object Number and object String respectively) while their literals will return primitives of types 'boolean', 'number' and 'string' respectively (and will behave differently in some situations), but array primitive type it is 'object' in any case.
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 11 years ago.
Possible Duplicate:
Length of Javascript Associative Array
I want to check the length of a multidimensional array but I get "undefined" as the return. I'm assuming that I am doing something wrong with my code but I can't see anything odd about it.
alert(patientsData.length); //undefined
alert(patientsData["XXXXX"].length); //undefined
alert(patientsData["XXXXX"]['firstName']); //a name
fruits = ["Banana", "Orange", "Apple", "Mango"];
alert(fruits.length); //4
Thoughts? Could this have something to do with scope? The array is declared and set outside of the function. Could this have something to do with JSON? I created the array from an eval() statement. Why does the dummy array work just fine?
Those are not arrays. They're objects, or at least they're being treated like objects. Even if they are Array instances, in other words, the "length" only tracks the largest numeric-indexed property.
JavaScript doesn't really have an "associative array" type.
You can count the number of properties in an object instance with something like this:
function numProps(obj) {
var c = 0;
for (var key in obj) {
if (obj.hasOwnProperty(key)) ++c;
}
return c;
}
Things get somewhat messy when you've got inheritance chains etc, and you have to work out what you want the semantics of that to be based on your own architecture.
.length only works on arrays. It does not work on associative arrays / objects.
patientsData["XXXXX"] is not an array. It's a object. Here's a simple example of your problem:
var data = {firstName: 'a name'};
alert(data.length); //undefined
It appears that you are not using nested array, but are using objects nested within objects because you're accessing members by their names (rather than indexes).