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).
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:
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
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 6 years ago.
I have found that these two different methods of creating an array of arrays produce different behaviors:
// Method 1
for (var arr1 = []; arr.push([]) < len;) {}
// Method 2
var arr2 = new Array(len).fill([])
The arrays created look the same in the console, however they behave differently in my code. What could be causing this?
The difference is that in the 1st method each index points to a different array, while in the Array#fill all indexes point to the same array.
Note: the 1st method will not create an array of arrays
var len = 3;
var arr1 = [];
// Method 1
for (var arr1 = []; arr1.push([]) < len;) {} // new sub array is pushed into arr1
// Method 2
var arr2 = new Array(len).fill([]) // each place in the array is filled with a reference to the same array
arr1[0].push(1); // push to the 1st element of arr1
arr2[0].push(1); // push to the 1st element of arr2
console.log('arr1: ', JSON.stringify(arr1)); // only the 1st sub array contains 1
console.log('arr2: ', JSON.stringify(arr2)); // all sub arrays contain 1
Update: While the answer below is technically accurate, and is another difference between the two methods, #Ori Drori's answer is almost certainly what the OP is looking for.
I'll take a stab at this, but more context would be helpful.
In common practice, these two statements typically behave the same, but there is a key difference - when you use the new keyword, the Javascript interpreter calls the Array constructor.
If you were to overwrite the Array constructor, this would only apply to arr2 which was defined with the new keyword. arr1 created with the array literal would still be a Javascript array.
As an example, let's say I wrote the following code:
function Array() {
}
Method 1 would still work, but Method 2 would return a TypeError indicating that fill is not a function.
Interestingly, using the Array literal (Method 1) still calls the Array constructor, so if I did a console.log("test"); within the Array construction this would still be printed to the console when using either method. BUT, when the Array literal (Method 1) is used, the object itself still remains a standard Javascript array even if the Array constructor is overwritten.
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:
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.