Related
Although counterintuitive, it is possible to create a JavaScript array "property" using dot notation:
const arr = [];
arr.dot = "notation";
console.log(arr.dot); // "notation"
Weird, but ok. However, the array's length still registers as 0:
const arr = [];
arr.dot = "notation";
console.log(arr.dot); // "notation"
console.log(arr.length); // 0
Two questions:
Why is the array's length not impacted by the property assigned via dot notation?
Why is it possible to assign a property to an array via dot notation?
A JavaScript array is just an object. You're setting the property dot on the object.
You can confirm that an array is an object by doing:
typeof arr.
The length property is computed based on the number of numeric entries in the array.
Here's an excerpt taken from developer.mozilla.org:
Arrays cannot use strings as element indexes (as in an associative array) but must use integers. Setting or accessing via non-integers using bracket notation (or dot notation) will not set or retrieve an element from the array list itself, but will set or access a variable associated with that array's object property collection. The array's object properties and list of array elements are separate, and the array's traversal and mutation operations cannot be applied to these named properties.
That dot notation is actually assigning a property to the array, not pushing a new value!
const myArray = ['apples', 'bananas'];
console.log(myArray);
myArray[2] = 'peach';
console.log(myArray);
I assume this is what made you look towards objects, which do this for assignment:
const myObject = {
id: 1,
name: 'Pig',
type: 'animal',
}
// Standard dot-notation assignment
myObject.sound = 'Oink!';
console.log(myObject);
// "Computed" assignment
myObject['emoji'] = '🐷';
console.log(myObject);
Here's a good read on the topic above https://ui.dev/computed-property-names/.
Back to the question at hand, though: why can't I do this:
const myArray = ['choclate', 'strawberry'];
myArray.pinapple = 'Tasty';
Arrays are essentially lists. It doesn't make sense to add an attribute (i.e. "describer") to a list.
Don't get me wrong - it is perfectly alright to set properties of an Array (as it is based off JavaScript objects), but it isn't used in the way that you're thinking of.
Here's an example of when I might use the "dot notation" assignment for an Array:
let zoo = ['Dolphin', 'Lion', 'Monkey'];
console.log(zoo);
// In-built property
console.log('I have', zoo.length, 'animals in my zoo!');
// Now, let's add a property "income"
zoo.income = 500;
console.log('My zoo has £%s', zoo.income);
// We can use this like a normal object property
zoo.income += 50;
console.log('My zoo has £%s', zoo.income);
// Let's create a method for when the zoo goes out of business
zoo.closeDown = () => {
zoo = [];
zoo.income = 0;
return true;
}
zoo.closeDown();
console.log(zoo);
console.log('My zoo has £%s', zoo.income);
Why would I want to do this? In this example, I could've used an object. But it's possible that it makes more sense to keep the animals in my zoo as an array, and then build up the methods and properties from there.
Okay, but how do I get a list of these properties/methods then?
const myArray = ['Foo', 'Bar'];
myArray.isCool = true;
console.log(myArray);
console.log(myArray.length);
let i;
for (i in myArray) {
console.log(i, myArray[i]);
}
The for (i in ...) syntax can be used here, as we are iterating through the properties of the array as an object. As we know from before, Arrays extend the Object class (kind of).
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in
length only counts the numeric properties.
Arrays are objects, so you can add other properties to them.
You don't even have to use dot notation, you can write arr["dot"] = "notation";
I am trying to check if an array of objects includes a object. I want it to return true when there is a object in the array that has the same values and the object id should not matter. This is how i thought it would work:
let arr = [{r:0, g:1}];
let obj = {r:0, g:1}
console.log(arr.includes(obj));
But it returns false and I need it to return true. Do I have to convert every object in the array to a string with JSON.stringify() and the object I am searching for like this:
let arr = [JSON.stringify({r: 0, g: 1})]
let obj = {r: 0, g: 1}
console.log(arr.includes(JSON.stringify(obj)));
Is there another easier and more efficient way to do it with more objects?
You get false because objects are compared by a reference to the object, while you got there 2 separate object instances.
Wile JSON.stringify might work, keep in mind that the order of properties is not guaranteed and it may fail if the order is not the same, because you get a different string.
you can check for an id property or compare several properties to match against, if you must you can compare all properties with a loop.
If you have an access to the object's reference, you can use a Map or a Set which allows you to store and check references
const obj = {r:0, g:1};
const obj2 = {r:0, g:1};
const mySet = new Set();
// given the fact that you do have access to the object ref
mySet.add(obj);
const isObjInList = mySet.has(obj);
const isObj2InList = mySet.has(obj2);
console.log('is obj in list - ', isObjInList);
console.log('is obj2 in list - ', isObj2InList);
JSON.stringify doesn't work as expected if you change the order of properties in one of the objects.
You can use .some in combination with isEqual from lodash (or other alternatives). Or you can write it by yourself, but be careful, there are too many edge cases, that's why I recommend using an existing approach. There is no need to reinvent the wheel.
let arr = [JSON.stringify({r: 0, g: 1})]
let obj = {g: 1, r: 0}
console.log(arr.includes(JSON.stringify(obj)));
let arr2 = [{r:0, g:1}];
let obj2 = {g:1, r:0};
console.log(arr2.some(item => _.isEqual(item, obj2)));
console.log(_.some(arr2, item => _.isEqual(item, obj2))); // more canonical way
<script src="https://cdn.jsdelivr.net/lodash/4/lodash.min.js"></script>
I like to use Set() for this purposes, read from the documentation:
The Set object lets you store unique values of any type, whether primitive values or object references.
See the below example:
let obj = {r:0, g:1};
const set = new Set();
set.add(obj);
console.log(set.has(obj));
I hope that helps!
You can use the JavaScript some() method to find out if a JavaScript array contains an object.
This method tests whether at least one element in the array passes the test implemented by the provided function. Here's an example that demonstrates how it works:
// An array of objects
var persons = [{name: "Harry"}, {name: "Alice"}, {name: "Peter"}];
// Find if the array contains an object by comparing the property value
if(persons.some(person => person.name === "Peter")){
alert("Object found inside the array.");
} else{
alert("Object not found.");
}
Note that if try to find the object inside an array using the indexOf() method like persons.indexOf({name: "Harry"}) it will not work (always return -1). Because, two distinct objects are not equal even if they look the same (i.e. have the same properties and values). Likewise, two distinct arrays are not equal even if they have the same values in the same order.
The some() method is supported in all major browsers, such as Chrome, Firefox, IE (9 and above), etc. See the tutorial on JavaScript ES6 Features to learn more about arrow function notation.
A method can get a value from an Array with the logic of that method. but length is not a method to an array, though returning a value when we write array.length, How?
"How did I get to know that .length is property to an array? is 'We all know that a method should have () when we are invoking a method, but .length don't invoke with (). so it is property to an object'".
var arr = [1,2,3,8,6,4,9,5,8,6];
console.log(arr.length); //10 -
console.log(Math.max(...arr)); //9
max() is returning a value because it is methode
As a property how does .length return a value?
Arrays are officially called "Array exotic objects". This sort of very weird behavior you're seeing, where an object property apparently changes itself automatically, is not visible (or possible to implement) on ordinary Javascript objects:
This specification defines several kinds of built-in exotic objects. These objects generally behave similar to ordinary objects except for a few specific situations. The following exotic objects use the ordinary object internal methods except where it is explicitly specified otherwise below:
and
An Array object is an exotic object that gives special treatment to array index property keys (see 6.1.7). A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 232. The value of the length property is numerically greater than the name of every own property whose name is an array index; whenever an own property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever an own property is added whose name is an array index, the value of the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the value of the length property is changed, every own property whose name is an array index whose value is not smaller than the new length is deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
In other words, an array's .length is a specific exception to the general rule that objects' properties do not change by themselves.
Note that getters can have a similar functionality:
const obj = {
get length() {
return Object.keys(this)
.filter(key => /^[0-9]+$/.test(key))
.length;
}
};
obj[0] = 'x';
obj[1] = 'y';
console.log(obj.length);
But an array's .length is not a getter, at least not visibly:
var arr = [1,2,3,8,6,4,9,5,8,6];
console.log(Object.getOwnPropertyDescriptor(arr, 'length'))
If it were a getter, you'd instead see a get property on the descriptor, like:
const obj = {
get length() {
return Object.keys(this)
.filter(key => /^[0-9]+$/.test(key))
.length;
}
};
console.log(Object.getOwnPropertyDescriptor(obj, 'length'))
Array length is all implemented under-the-hood, and not visible to the running Javascript.
You could take a property and assign or get a value from it, but it is iomplementes as setter and getter. This allows to use a function as simple property and uses the assigned value for changing other things, like to remove items.
var object = {
l: 42,
get length() { return this.l; },
set length(l) { this.l = l; },
}
console.log(object.length);
object.length = 2;
console.log(object.length);
Good Question. The only catch here is that you believe Array.length is calculated when you invoke/call this property. No, it does not happen like that.
When an Array is created, it's properties get set. These properties like length, prototypical functions etc. contain a value when an Array is created. When you execute Array.length, you are only getting the value of that property. In case of functions, the code execution happens when you invoke the call.
Think of it like a constructor in the Array definition which sets the property length as soon as an object of Array class is created and modified.
The length property of an object which is an instance of type Array
sets or returns the number of elements in that array. The value is an
unsigned, 32-bit integer that is always numerically greater than the
highest index in the array.
As stated, you can also use it to set the number of elements. This is achievable using a getter and setter by theory.
The following example sets the latest property of an object which will represent the last element of an internal array.
var obj = {
log: ['a', 'b', 'c'],
get latest() {
if (this.log.length == 0) {
return undefined;
}
return this.log[this.log.length - 1];
},
set latest(val) {
this.log[this.log.length - 1] = val;
}
}
obj.latest = 'z';
console.log(obj.latest);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JavaScript: Check if object is array?
Why is an array of objects considered an object, and not an array? For example:
$.ajax({
url: 'http://api.twitter.com/1/statuses/user_timeline.json',
data: { screen_name: 'mick__romney'},
dataType: 'jsonp',
success: function(data) {
console.dir(data); //Array[20]
alert(typeof data); //Object
}
});
Fiddle
One of the weird behaviour and spec in Javascript is the typeof Array is Object.
You can check if the variable is an array in couple of ways:
var isArr = data instanceof Array;
var isArr = Array.isArray(data);
But the most reliable way is:
isArr = Object.prototype.toString.call(data) == '[object Array]';
Since you tagged your question with jQuery, you can use jQuery isArray function:
var isArr = $.isArray(data);
Quoting the spec
15.4 Array Objects
Array objects give special treatment to a certain class of property names. A property name P (in the form of a String value) is an array index if and only if ToString(ToUint32(P)) is equal to P and ToUint32(P) is not equal to 2^32-1. A property whose property name is an array index is also called an element. Every Array object has a length property whose value is always a nonnegative integer less than 2^32. The value of the length property is numerically greater than the name of every property whose name is an array index; whenever a property of an Array object is created or changed, other properties are adjusted as necessary to maintain this invariant. Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index; and whenever the length property is changed, every property whose name is an array index whose value is not smaller than the new length is automatically deleted. This constraint applies only to own properties of an Array object and is unaffected by length or array index properties that may be inherited from its prototypes.
And here's a table for typeof
To add some background, there are two data types in JavaScript:
Primitive Data types - This includes null, undefined, string, boolean, number and object.
Derived data types/Special Objects - These include functions, arrays and regular expressions. And yes, these are all derived from "Object" in JavaScript.
An object in JavaScript is similar in structure to the associative array/dictionary seen in most object oriented languages - i.e., it has a set of key-value pairs.
An array can be considered to be an object with the following properties/keys:
Length - This can be 0 or above (non-negative).
The array indices. By this, I mean "0", "1", "2", etc are all properties of array object.
Hope this helped shed more light on why typeof Array returns an object. Cheers!
Try this example and you will understand also what is the difference between Associative Array and Object in JavaScript.
Associative Array
var a = new Array(1,2,3);
a['key'] = 'experiment';
Array.isArray(a);
returns true
Keep in mind that a.length will be undefined, because length is treated as a key, you should use Object.keys(a).length to get the length of an Associative Array.
Object
var a = {1:1, 2:2, 3:3,'key':'experiment'};
Array.isArray(a)
returns false
JSON returns an Object ... could return an Associative Array ... but it is not like that
This is more of a general question than a problem I need solved. I'm just a beginner trying to understand the proper way to do things.
What I want to know is whether or not I should only use objects as prototypes (if that's the correct term to use here) or whether or not it's OK to use them to store things.
As an example, in the test project I'm working on, I wanted to store some images for use later. What I currently have is something like:
var Images = {
james: "images/james.png",
karen: "images/karen.png",
mike: "images/mike.png"
};
Because I would know the position, I figure I could also put them in an array and reference the position in the array appropriately:
var images = ["images/james.png", "images/karen.png", "images/mike.png"];
images[0];
Using the object like this works perfectly fine but I'm wondering which is the more appropriate way to do this. Is it situational? Are there any performance reasons to do one over the other? Is there a more accepted way that, as a new programmer, I should get used to?
Thanks in advance for any advice.
Introduction
Unlike PHP, JavaScript does not have associative arrays. The two main data structures in this language are the array literal ([]) and the object literal ({}). Using one or another is not really a matter of style but a matter of need, so your question is relevant.
Let's make an objective comparison...
Array > Object
An array literal (which is indirectly an object) has much more methods than an object literal. Indeed, an object literal is a direct instance of Object and has only access to Object.prototype methods. An array literal is an instance of Array and has access, not only to Array.prototype methods, but also to Object.prototype ones (this is how the prototype chain is set in JavaScript).
let arr = ['Foo', 'Bar', 'Baz'];
let obj = {foo: 'Foo', bar: 'Bar', baz: 'Baz'};
console.log(arr.constructor.name);
console.log(arr.__proto__.__proto__.constructor.name);
console.log(obj.constructor.name);
In ES6, object literals are not iterable (according to the iterable protocol). But arrays are iterable. This means that you can use a for...of loop to traverse an array literal, but it will not work if you try to do so with an object literal (unless you define a [Symbol.iterator] property).
let arr = ['Foo', 'Bar', 'Baz'];
let obj = {foo: 'Foo', bar: 'Bar', baz: 'Baz'};
// OK
for (const item of arr) {
console.log(item);
}
// TypeError
for (const item of obj) {
console.log(item);
}
If you want to make an object literal iterable, you should define the iterator yourself. You could do this using a generator.
let obj = {foo: 'Foo', bar: 'Bar', baz: 'Baz'};
obj[Symbol.iterator] = function* () {
yield obj.foo;
yield obj.bar;
yield obj.baz;
};
// OK
for (const item of obj) {
console.log(item);
}
Array < Object
An object literal is better than an array if, for some reason, you need descriptive keys. In arrays, keys are just numbers, which is not ideal when you want to create an explicit data model.
// This is meaningful
let me = {
firstname: 'Baptiste',
lastname: 'Vannesson',
nickname: 'Bada',
username: 'Badacadabra'
};
console.log('First name:', me.firstname);
console.log('Last name:', me.lastname);
// This is ambiguous
/*
let me = ['Baptiste', 'Vannesson', 'Bada', 'Badacadabra'];
console.log('First name:', me[0]);
console.log('Last name:', me[1]);
*/
An object literal is extremely polyvalent, an array is not. Object literals make it possible to create "idiomatic" classes, namespaces, modules and much more...
let obj = {
attribute: 'Foo',
method() {
return 'Bar';
},
[1 + 2]: 'Baz'
};
console.log(obj.attribute, obj.method(), obj[3]);
Array = Object
Array literals and object literals are not enemies. In fact, they are good friends if you use them together. The JSON format makes intensive use of this powerful friendship:
let people = [
{
"firstname": "Foo",
"lastname": "Bar",
"nicknames": ["foobar", "barfoo"]
},
{
"firstName": "Baz",
"lastname": "Quux",
"nicknames": ["bazquux", "quuxbaz"]
}
];
console.log(people[0].firstname);
console.log(people[0].lastname);
console.log(people[1].nicknames[0]);
In JavaScript, there is a hybrid data structure called array-like object that is extensively used, even though you are not necessarily aware of that. For instance, the good old arguments object within a function is an array-like object. DOM methods like getElementsByClassName() return array-like objects too. As you may imagine, an array-like object is basically a special object literal that behaves like an array literal:
let arrayLikeObject = {
0: 'Foo',
1: 'Bar',
2: 'Baz',
length: 3
};
// At this level we see no difference...
for (let i = 0; i < arrayLikeObject.length; i++) {
console.log(arrayLikeObject[i]);
}
Conclusion
Array literals and object literals have their own strengths and weaknesses, but with all the information provided here, I think you can now make the right decision.
Finally, I suggest you to try the new data structures introduced by ES6: Map, Set, WeakMap, WeakSet. They offer lots of cool features, but detailing them here would bring us too far...
Actually, the way you declared things brings up the "difference between associative arrays and arrays".
An associative array, in JS, is really similar to an object (because it's one):
When you write var a = {x:0, y:1, z:3} you can access x using a.x(object) or a["x"](associative array).
On the other hand, regular arrays can be perceived as associative arrays that use unsigned integers as ID for their indexes.
Therefore, to answer your question, which one should we pick ?
It depends : I would use object whenever I need to put names/labels on thing (typically not for a collection of variables for instance). If the type of the things you want to store is homogeneous you will probably use an array (but you can still go for an object if you really want to), if some of/all your things have a different type than you should go for an object (but in theory you could still go for an array).
Let's see this :
var a = {
x:0,
y:0,
z:0
}
Both x,y,z have a different meaning (components of a point) therefore an object is better (in terms of semantic) to implement a point.
Because var a = [0,0,0] is less meaningful than an object, we will not go for an array in this situation.
var storage = {
one:"someurl",
two:"someurl2",
three:"someurl3",
}
Is correct but we don't need an explicit name for every item, therefore we might choose var storage = ["someurl","someurl2","someurl3"]
Last but not least, the "difficult" choice :
var images = {
cathy: "img/cathy",
bob: "img/bob",
randompelo: "img/randompelo"
}
and
var images = ["img/cathy","img/bob","img/randompelo"]
are correct but the choice is hard. Therefore the question to ask is : "Do we need a meaningful ID ?".
Let's say we work with a database, a meaningful id would be better to avoid dozens of loops each time you wanna do something, on the other hand if it's just a list without any importance (index is not important, ex: create an image for each element of array) maybe we could try and go for an array.
The question to ask when you hesitate between array and object is : Are keys/IDs important in terms of meaning ?
If they are then go for an object, if they're not go for an array.
You're correct that it would be situational, but in general its not a good idea to limit your program by only allowing a finite set of supported options like:
var Images = {
james: "images/james.png",
karen: "images/karen.png",
mike: "images/mike.png"
};
Unless, of course, you happen to know that these will be the only cases which are possible - and you actively do not want to support other cases.
Assuming that you dont want to limit the possibilities, then your array approach would be just fine - although personally I might go with an array of objects with identifiers, so that you arent forced to track the index elsewhere.
Something like:
var userProfiles = [
{"username": "james", "image": "images/james.png"},
{"username": "karen", "image": "images/karen.png"},
{"username": "mike", "image": "images/mike.png"}
];