Counting length of another object property within object function -- JavaScript? [duplicate] - javascript

This question already has answers here:
Length of a JavaScript object
(43 answers)
Closed 6 years ago.
I am new to JavaScript objects so please bear with me.
This is my JavaScript:
var dragSources = {
elementSources: {
squareSource: document.getElementById('squareSource'),
circleSource: document.getElementById('circleSource')
},
ifDragSource: function(elem) {
console.log(this.elementSources.length);
}
};
If you look at console.log(this.elementSources.length); you can probably tell that I am trying to get the length of the elementSources property. However, it returns undefined. What am I doing wrong?

It's an object, not an array, therefore it doesn't have a length property.
You could use Object.keys(this.elementSources).length to get the number of keys.
The .keys() method essentially returns an array of the object's keys.
In this case, Object.keys(this.elementSources) returns:
["squareSource", "circleSource"]
Then we are just getting the length of that array, which is 2.
var dragSources = {
elementSources: {
squareSource: document.getElementById('squareSource'),
circleSource: document.getElementById('circleSource')
},
ifDragSource: function(elem) {
console.log(Object.keys(this.elementSources).length);
}
};
dragSources.ifDragSource(); // 2

Technically if you need the length property in a code you have to store the length value directly in the object.
Using Object.key function decreases the code efficiency .
every time you invoke that function to access that value you have to re-run the same function again and again.
in order access to the length property in a js array, the BIG O is always equal to 1.
because when you update the array the length property would be updated consequently
But in that case the big O would be in the size of the Object and (O) = n

Related

I can't iterate over a javascript array [duplicate]

This question already has answers here:
How can JavaScript arrays have non-numeric keys?
(2 answers)
How do I loop through or enumerate a JavaScript object?
(48 answers)
Closed 4 months ago.
I am going crazy here, I have an associative array as seen below which is defined after the page finishes loading. However Array.forEach is returning undefined and I have no idea why. The array is most definitely populated during the loop. Can anyone give me any ideas? Also doesn't work with JQuery's $.each
Arrays are usually a mapping of index (integer from 0 to 232 − 2, inclusive) to value. In your case you've treated the array as a dictionary e.g. key (string) to value.
You've probably done something like this:
members = new Array();
members['animerox1213'] = 'Ashima';
JavaScript allows this, after all it is still an object:
typeof members === 'object'
But instead of adding a value to the array, you've actually set a non-numeric property on the object called animerox1213. That is not how an array should be used and we can observe this by checking the size:
members.length === 0;
Consequently, forEach does not do anything as it considers it an empty array.
That said, it is enumerable with for…in as it's still just an object (with enumerable properties):
for (m in members) {
console.log(m, members[m]);
}
Consider using just an object e.g. members = {} or Map. Note especially the section Objects vs. Maps.

How does the array get updated on updating the property 'length' of the array in JavaScript? [duplicate]

This question already has answers here:
How length property of an array works in javascript?
(7 answers)
Is the JavaScript Array.length property a function or a simple variable?
(7 answers)
Array.length is a property not a method, but how .length is work like a method?
(4 answers)
Closed 3 months ago.
My question is if I use an array like this,
var arr1 = [1, 2, 3, 4];
console.log(arr1.length); // 4 (Expected)
If I update the length property, the array gets updated too.
arr1.length = 0;
console.log(arr1); // []
I'd like to know how this is being done (the internals)?
Also, I'm not sure if getter and setter methods of the property length (that are ways to run a function if the property gets accessed or set) are used here. I think they're not.
If it's being used, length should not be visible directly when I expand the array in the browser console. But we get the length directly without running any functions.
The console when I use get/set for a property of an object,
Getting the value of length property directly without running any functions,

How to access a particular path/adress inside an object? [duplicate]

This question already has answers here:
access object through dot-syntax string path
(2 answers)
Convert a JavaScript string in dot notation into an object reference
(34 answers)
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 2 years ago.
I am having a problem which I think I might have figured out before how to do it but I can't remember now and can't figure it out.
Let's say we have an object thats a few levels deep, meaning it has as values other objects which also have as some of the values objects and so on.
Now how could I make a function to which I pass the object and and adress inside it and I can access the value at that location inside the function like this:
const getValueAtAdress = (object, 'country.city.rules') => {
return //here I need to return the value at object.country.city.rules.
}
Am I missing something obvious?
I thought I'd mention here for posterity that what helped me was the answer using the reduce which is exactly what I used before but I could not remember:
Example that I am using for my particular problem:
let stateLocation = address.split('.').reduce((acc, cur) => acc[cur], state);
Your code shows a function declaration but you can't declare an argument name in quotes
You can however call a function and pass a string.
In that case, you just need to split the string into an array and then loop over that array, building up a "chained" set of string indexes that can be passed to the object. The String.split() and Array.reduce() methods are the key.
let obj = {
county: {
city: {
rules: "Strict"
}
}
};
const getValueAtAddress = (object, countyCityRules) => {
// Split the string at the dots to form an array...
// The loop over that array and reduce it with an
// accumulator that is then applied to the object.
return countyCityRules.split(".").reduce((acc, cur) => acc[cur], obj);;
}
console.log(getValueAtAddress(obj, "county"));
console.log(getValueAtAddress(obj, "county.city"));
console.log(getValueAtAddress(obj, "county.city.rules"));

Why does JavaScript allow accessing an object's property using an array of length 1, as if the array was just the single element itself? [duplicate]

This question already has answers here:
Why does JavaScript convert an array of one string to a string, when used as an object key? [duplicate]
(4 answers)
Why can I access object property with an array?
(2 answers)
Closed 2 years ago.
See this example:
> map = { 5: 'five' }
> map[5]
'five' // Makes sense
> arr = [5]
> map[arr]
'five' // Does not make sense
> arr = [5,6,7]
> map[arr]
undefined // I'm cool with that
So when I access an object's property with an array of length 1, it behaves as if I simply input the single element instead of the array. But when the array's length is anything but 1, it will produce the expected behavior.
What is the purpose of this behavior? To me this would simply make things harder for a developer to find a bug in their code.
If an object index is not a string or Symbol, it's converted to a string as if by its toString() method.
array.toString() performs the equivalent array.join(",").
So
map[arr]
is equivalent to
map[arr.join(",")]
If the array has one element, joining it simply returns that one element converted to a string, so it's equivalent to
map[arr[0].toString()]
and that explains your first result.
But in your second example, it returns the string "5,6,7" and there's no property with that name in the object.

Difference between "new Array(..)" and "[..]" in JavaScript? [duplicate]

This question already has answers here:
What’s the difference between "Array()" and "[]" while declaring a JavaScript array?
(19 answers)
Closed 8 years ago.
Is
var myCars=new Array("Saab","Volvo","BMW");
and
var myCars=["Saab","Volvo","BMW"];
exactly the same ?
Yes, for that case they are the same.
There is a difference if you have only one item, and it's numeric. This will create an array with a single item:
var myNumbers = [42];
but this will create an array with the length 42:
var myNumbers = new Array(42);
Yes, they are. However be aware that when you pass just a single numeric parameter to the Array constructor, you will be specifying the initial length of the array, instead of the value of the first item. Therefore:
var myCars1 = new Array(10);
... will behave differently from the following array literal:
var myCars2 = [10];
... note the following:
console.log(myCars1[0]); // returns undefined
console.log(myCars1.length); // returns 10
console.log(myCars2[0]); // returns 10
console.log(myCars2.length); // returns 1
That is one reason why it is often recommended to stick to the array literal notation: var x = [].
Yes, they are the same. There is no primitive form of an Array, as arrays in JavaScript are always objects. The first notation (new Array constructor syntax) was used heavily in the early days of JavaScript where the latter, short notation was not supported well.
Note that there is one behavioural difference: if you pass a single, numeric argument to new Array, like new Array(20), it will return a new array pre-initialised with that number of elements from 0 to n - 1, set to undefined.

Categories