Difference between array and arrayvalue [duplicate] - javascript

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
How do you check if a variable is an array in JavaScript?
How can I check if a variable is an array (so I can handle each arrayvalue) or a single arrayvalue?

From the MDN page for isArray which is part of the ECMAScript 5 standard:
if(!Array.isArray) {
Array.isArray = function (arg) {
return Object.prototype.toString.call(arg) == '[object Array]';
};
}
In many cases, you can also just check to see if there is a .length property (this is often what jQuery does) because this will also accept any array-like object that isn't actually an array, but can be iterated like one. Obviously, if you have things that do have a .length property that you don't want treated like an array, this will get fooled by that situation so you have to know which you want:
function isArrayLike(item) {
return(typeof item.length != "undefined");
}

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.

JS array.includes() // array within array // [['a']].includes(['a']) returns false [duplicate]

This question already has answers here:
Why can't I use Array#includes for a nested array?
(5 answers)
How to compare arrays in JavaScript?
(61 answers)
Closed 3 months ago.
TL;DR: the JavaScript code below returns false where I'm expecting a true, what's the best workaround?
console.log([['a']].includes(['a']))
I'm pushing arrays into arrays (to work with google sheets ranges in apps script, but the behaviour is the same in regular JavaScript).
I'd like to check if my parent array (let's call it [['a']]) contains specific child array (such as ['a']).
Unfortunately array.includes() doesn't seem to work as expected when the parameter is an array. (the code above returns false when it should be true as far as I know)
Am I missing anything? What do you think would be the best workaround?
The problem is array comparison.
console.log(['a'] == ['a']); //false
As the .includes() method loops through the array on which it is being called, it checks each element to see if it is equal to the value being tested for, until it finds a match, or checks every element of the array. As you can see above, when the value being tested is an array, it will not work.
A work around would be to write your own .includes() function in which you loop through all the child arrays in the parent array, and for each child array, loop through every element, testing whether it is equal to the corresponding element in the test array. You can use the .every() method for this.
let array = [['a']];
function includesArray(parentArray, testArray) {
for (let i = 0; i < parentArray.length; i++) {
if (parentArray[i].every(function(value, index) { return value === testArray[index]})) {
return true;
}
}
return false;
}
console.log(includesArray(array, ['a'])); //true
console.log(includesArray(array, ['b'])); //false
One quick alternative is to compare the JSON strigified arrays instead of comparing arrays directly.
console.log([['a']].map(x => JSON.stringify(x)).includes(JSON.stringify(['a'])))

Why does {} == {} equals false? [duplicate]

This question already has answers here:
Why are two identical objects not equal to each other?
(9 answers)
Closed 4 years ago.
Short question about JavaScript. I tried to execute {} == {} in JavaScript and expected to get true, but it didn't and I want to understand why. Shouldn't {} == {} return true and {} === {} return false?
Because == and === check if the two compared variables are references to the same object, not whether they are identical in value.
Thus a two variables internally referencing each other or a third variable are both == and ===, two new instances of an object are not.
To check if two objects are identical, you could JSON.stringify() them and check whether or not the results are the same.
Most common libraries for JavaScript contain a function to compare two objects, in vanilla JS you can make such a function for yourself:
Object.compare = function(obj1, obj2) {
if (obj1 && obj2) return JSON.stringify(obj1) === JSON.stringify(obj2)
}
console.log(
Object.compare({foo:"bar"}, {foo:"bar"})
);
When comparing two objects with ===, the references will be checked.
These are not two references to the same obejcts, these are two different instances of an empty object.
When comparing with ==, there might be usually some coercion to some common type prior to comparison, following specific rules that are too complicated to be listed here.
But long story short, since you are compariong two objects, there won't be a different check.

Why does {} == {} return false? [duplicate]

This question already has answers here:
Why are two identical objects not equal to each other?
(9 answers)
Closed 3 years ago.
I was writing a script, and I had something like
var myObject = {};
if (myObject == {}){
...
}
I was surprised to find that this evaluated to false.
My own findings
Reading up on some of the funny querks javascript does, I found this article, which tells that {} will result in a "truthy" object in an if statement, for example
if ({}){ // true
...
}
Hm, well further ready discuesses String Equality, which for object comparison, says it will return true if they reference the same object. (Even {} === {} returns false)
The only reason I can think that is would return false is that the objects are technically at different memory address, and thus considered different objects.
Because every {} creates a unique object. You can't compare them that way.

Array comparison failure [duplicate]

This question already has answers here:
How to compare arrays in JavaScript?
(55 answers)
Closed 9 years ago.
Long story short. Why is
console.log(obj.hello[0].w == ['hi','hi']); // false
in the following:
var obj = {
'hello':[
{'w':['hi','hi']}
]
}
console.log(obj.hello[0].w); // ['hi','hi']
console.log(obj.hello[0].w == ['hi','hi']); // false ??? Why is it false?
console.log(obj.hello[0].w[0] == 'hi'); // true
console.log(obj.hello[0].w[0] == ['hi']); // true
console.log(obj.hello[0].w[0] === ['hi']); // false
console.log(obj.hello[0].w[0] === 'hi'); // true
If obj.hello[0].w != ['hi','hi'], then what is the 'real' value of obj.hello[0].w?
EDIT: I first thought the problem was about JSON but it turned out it's about comparing objects. Sorry, for duplicate.
In addition to #MightyPork's answer, there are workarounds that are very simple.
The easiest way (supported by modern browsers) is to use JSON.stringify().
JSON.stringify(['hi', 'hi')) === JSON.stringify(['hi', 'hi')) // true
If your browser doesn't support JSON nativley you can include the JSON-js library on your page, which has the same syntax.
This isn't a complete solution. For example, functions always return null, except when they are class instances.
function a(){ this.val = "something"; }
JSON.stringify([a]) // "[null]"
JSON.stringify([new a]) // "[{"val":"something"}]"
You cannot compare arrays like if they were simple variables. You're comparing references to two different arrays, and that will always be false, regardless of their contents.
If you want to do the check, you will have to compare each value individually.

Categories