This question already has answers here:
JavaScript property access: dot notation vs. brackets?
(17 answers)
Are Javascript arrays primitives? Strings? Objects?
(7 answers)
Closed 2 years ago.
I'm looking for an elegant way of understanding JavaScript array and objects.
I came to an anomaly in which I got stuck.
Since in PHP or other languages, when we make an array e.g
$a = [
admin => 1,
staff => 2
];
so if we want to access its element we can do so by for e.g $a[admin] and we will get 1.
similarly if its an object e.g
$a = (object) [];
$a->sadd = 'sas';
we can access it with arrow
$a->sadd
and if we try to access object elements in the style of array i.e like this $a['sadd'] it will throw error that you can not use it as array style.
But I was surprised by the anomaly in JavaScript.
I have observed that in JavaScript no matter what I am making, an array or object, the elements of both can be accessed via dot or via array style and i found no difference in there accessing style.
for e.g
var a = {sadd : 1}
I can access its element via a['sadd'] or a.sadd both will give 1
So I am confused by this anomaly and wondering whether array and object both datatypes are considered same in JavaScript?
An array is indeed an object.
Javascript is a dynamic language and accepts mixed types of entities. Also while accessing, dot notation seems to be more clearer (atleast imo) and is preferred. Bracket notation is used for dyanamic keys.
The difference between array and objects boils down to their usecase:
Array -> Contiguous block of memory
Object -> key-value pair (like a dictionary)
Your php example is actually creating what we'd call an object in JS, not an array. In JS an array is a list of items, which you can find items by array[i], or by looping.
An object is a collection of fields, which you can go into by object.fieldName or object[fieldName].
This can be confusing in JS though, because theoretically everything is an "object", including arrays, due to the way things are handled lower down..
I would recommend following along with the https://justjavascript.com/ course for good mental models on how objects work in JS.
Related
This question already has answers here:
Why can I add named properties to an array as if it were an object?
(8 answers)
Closed 3 months ago.
I noticed that Javascript allows you to add a name/value (or key/value) pair inside already-made regular arrays (not objects). Why is this allowed? Is there an intention behind this? Is this another data type? I understand this is neither an object nor an associative array (which is really an object). I know arrays are objects too, and in this case JS is allowing me to use a string instead of a number as a key, but this would put the data in an odd category which is neither a regular array nor an object.
array1 = ['a', 'b', 'c']
array1.propertyName = 'property value'
console.log(array1); // [ 'a', 'b', 'c', propertyName: 'property value' ]
This question was already addressed in How to create an associative array in JavaScript literal notation, but no real answer was given rather than "You need to use an object". I already use objects in JS, I am just curious about this behaviour in arrays.
Thank you!
You can assume pair is just a value. Value inside a value is normal unless if you are using static typed languange.
Why is that allowed? computer take any argument u pass as a value despite it having a pair, array or an object. Doesn't matter.
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.
This question already has answers here:
How do I replace a character at a particular index in JavaScript?
(30 answers)
Does javascript have a method to replace part of a string without creating a new string?
(4 answers)
Closed 1 year ago.
var a = 'cat' ;
a[0] = 'r' ;
a = 'cat'
Why..??
In case of string although you can access elements by array notation, if you try to change its content it will fail silently i.e. will not throw any error but will not change content either.
Please explain me detail.
Strings are primitive values in javascript, and are therefore immutable. This is just how the language works so there's not much to explain besides that. You can read more about it here!
It is not throwing an error because you're probably not running it in strict mode.
Strings are immutable, in JavaScript only objects and arrays are mutable. You can search for mutable data types in JavaScript in Google.
"A mutable object is an object whose state can be modified after it is created." MDN.
You can read more here: Mutable
This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 2 years ago.
So this is a bit of an unusual situation i am in but what i need to do is access the value of an object based on what index its stored in. The problem is that i need it in my Select component of material ui. So the overview is that i store alginment values of a video . the videos show up in a loop which means the select values are repeated and to know if its for the first video i append the index inside the object like this:
Now in order to set the option i have to access this value here :
Now the problem is in this loop i cant do something like :
halign.halign[index] because obviously that would mean its an array. So long story short how could i do something like :
value={`${halign.halign}${index}`}
So basically the end result for value to evaluate is : halign.halign0
and so on for each index.
NOTE the outer halign is the main useState object.
Remember that for JavaScript objects x['y'] and x.y are interchangeable.
So if you need to compute the key you're looking up, use:
halign['halign' + index]
Or template strings if you prefer.
Note this would be a lot easier if you organized your object with an internal array, so you could just do halign[index].
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 8 years ago.
Hello I am doing a school assignment my main problem is as follows.
var objectQueue = {
customers:[
{name:"Phil", order:"coffee"},
{name:"Sandy", order:"coffee"},
{name:"Enrique", order:"sandwich"},
{name:"Joe", order:"coffee"},
{name:"Alex", order:"muffin"},
{name:"Zoe", order:"chili"},
{name:"Bahamut", order:"sandwich"},
{name:"Rydia", order:"timbits"}
]
};
I have this object, I need to know how to access each customer's order through a for loop. I can't get the loop to read each person's order. What would be the right way to do this?
This is where I am currently:
objectQueue[x]order
Assuming x is a counter:
objectQueue.customers[x].order
objectQueue has a property named customers, to access a simple property on a Javascript object, you can just use its name:
objectQueue.customers
Then, customers has a array of objects. To access elements in a array, we use its index:
customers[0]
Since the elements in the list are maps/objects, we can access them via properties as well:
customers[0].name
Putting this all together we get:
objectQueue.customers[0].name
Almost everything in Javascript is an object, so it's a little misleading to differentiate between arrays and objects (since arrays ARE objects), but I'm assuming you can dig into those details later if you're interested. In the meantime, this should get you going.
You first need to access the length of the customers and use that as your loop count, from there you can use 'i' your counter to access properties
for (i=0; i<objectQueue.customers.length; i++){
console.log(objectQueue.customers[i]);
console.log(objectQueue.customers[i].name);
console.log(objectQueue.customers[i].order);
}