This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 9 years ago.
I'm not sure what they are called, but what I mean is this:
array["water"] = 50;
array["fire"] = 30;
length should be 2 here
how can I see how many attributes I have in the array? array.length doesn't work =( I've been trying all kinds of things and I feel like I'm missing something really simple here..
Thank you for your help
You could use Object.keys() to obtain an array of keys, then count them:
Object.keys(array).length
Or, if you're targeting ECMAScript 3 or otherwise don't have Object.keys(), then you can count the keys manually:
var length = 0;
for (var key in array) {
if (array.hasOwnProperty(key)) {
++length;
}
}
There are a few edge cases with this approach though, depending on the browsers you're targeting, so using Mozilla's polyfill for Object.keys() instead might be a good idea.
Related
This question already has answers here:
How to iterate over a WeakMap?
(3 answers)
Closed 9 months ago.
I have a WeakMap like this:
let obj = new WeakMap();
let objKey1={"a":1};
let objKey2={"b":2};
let objKey3={"c":3};
obj.set(objKey1,"value1");
obj.set(objKey2,"value2");
obj.set(objKey3,"value3");
Is there a way to get the length / number of keys stored in obj?
I tried Object.keys(obj).length but it returns 0
From the documentation
But because a WeakMap doesn't allow observing the liveness of its keys, its keys are not enumerable. There is no method to obtain a list of the keys.
It should therefore follow that there is no way to get the number of keys either.
This question already has answers here:
Explanation of [].slice.call in javascript?
(9 answers)
Closed 1 year ago.
Bootstrap 5 Javascript examples sometimes show code like:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'))
Why isn't this just:
var collapseElementList = document.querySelectorAll('.collapse')
What is [].slice.call() doing exactly? I don't understand why you'd slice on an empty array, and then I have no idea what call is doing there. What would be the problem with the obvious way to do this, the second way above?
querySelectorAll returns a NodeList, which is a collection, but not an array.
[].slice.call turns an array-like collection into an array proper. It will allow you to use array methodss on it, eg:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'));
const textsOfCollapsedElements = collapseElementList.map(elm => elm.textContent);
Otherwise, if you don't convert it to an array first, you won't be able to use array methods on it.
It's probably most important for forEach. Newer browsers support NodeList.prototype.forEach, but it hasn't been with us that long. In contrast, Array.prototype.forEach has existed forever. So turning the collection into an array allows for forEach to be called on it, even on obsolete browsers that don't support NodeList.prototype.forEach.
It's an idiom for turning anything array-ish (in this case a DOM NodeList) into a real Array by exploiting the fact that Array::slice can work on anything that's iterable and has a .length property.
The modern idiom is Array.from(...).
This question already has answers here:
Why is using "for...in" for array iteration a bad idea?
(28 answers)
JavaScript: Why does the "for in" loop pick variables from __proto__?
(4 answers)
Loop through an array in JavaScript
(46 answers)
Loop (for each) over an array in JavaScript
(40 answers)
Closed 8 months ago.
The code which worked before was failing now in for loop after I added enyo.js. I suspect that when I use for(var ls in list) it loops through even when length is 0. When I put the debugged I found out that it is considering "findIndex" as one of value in list and goes into the loop. I have several places using for with in, I want to find out a best way to filter out "findIndex" or any invalid indexes so that only valid elements go into the loop
for(var ls in list)
{
var lin = list[ls].rb ;
}
If you list is an array, just use a regular for loop. It's generally not a great idea to use for...in with an array for exactly this reason and also because the order isn't guaranteed.
If you must use for...in use a hasOwnProperty check:
for (var ls in list)
{
if (list.hasOwnProperty(ls)) {
var lin = list[ls].rb;
// ...
}
}
Of course, if you only concern is whether you have an rb property, you could just test for that:
if (list[ls].rb) {
var lin = list[ls].rb;
}
Or even:
var lin = list[ls].rb;
if (lin) {
// do whatever you needed to do with lin
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Length of Javascript Associative Array
hash_table = {a: 131, b: 222, c:313}
The length method is not working of course since it will be confused with a key.
So how do I do it?
Object.keys will return all the keys in the object as a list, then use length to get the length.
example:
Object.keys(hash_table).length
NOTE that this is ECMA 5 and may not be available in some browsers. see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/keys for full document.
var count = 0;
for ( property in hash_table ) count++;
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
JavaScript “For …in” with Arrays
I'm trying to use the for-in syntax to loop through an array of numbers. Problem is, those numbers are getting converted to strings.
for(var element in [0]) {
document.write(typeof(element)); // outputs "string"
}
Is this standard behavior? I can think of a bunch of ways to work around it, but I'm really just looking for an explaination, to expand my understanding of JavaScript.
I think you misunderstand what JavaScript for...in does. It does not iterate over the array elements. It iterates over object properties. Objects in JavaScript are kind of like dictionaries or hashes in other languages, but keyed by strings. Arrays in particular are implemented as objects which have properties that are integers from 0 to N-1 - however, since all property names are strings, so are the indices, deep down.
Now let's take a bit different example than [0], since here index coincides with the value. Let's discuss [2] instead.
Thus, [2] is, if we ignore the stuff we inherit from Array, pretty much the same as { "0": 2 }.
for..in will iterate over property names, which will pick up the "0", not the 2.
Now, how to iterate over Arrays then, you ask? The usual way is:
var arrayLen = array.length;
for (var i = 0; i < arrayLen; i++) {
var el = array[i];
// ...
}
This is a repeat of Why is using "for...in" with array iteration a bad idea?
The for-in statement enumerates the properties of an object. In your case element is the name of the property and that is always a string.