How to know whether an object is array or not?
var x=[];
console.log(typeof x);//output:"object"
alert(x);//output:[object Object]
console.log(x.valueOf())//output:<blank>? what is the reason here?
console.log([].toString()); also outputs <blank>
Object.prototype.toString.call(x) output:[object Array] how?
since console.log([].toString()); outputs :blank
1st:
why i get blank at 2nd last statement?
2nd:
Is there a way to know exactly what an object is: Array or plain Object({}) without the help of their respective methods like x.join() indicates x is an Array,not in this way.
Actually,in jquery selection like $("p") returns jquery object so if i use
console.log(typeof $("p"));//output:"object
I just wanted to know the actual Name of the Object.Thats it.Thank u for u help
In pure JavaScript you can use the following cross browser approach:
if (Object.prototype.toString.call(x) === "[object Array]") {
// is plain array
}
jQuery has special method for that:
if ($.isArray(x)) {
// is plain array
}
You can use instanceof
. Here's some FireBug testing:
test1 = new Object();
test2 = new Array();
test3 = 123;
console.log(test1 instanceof Array); //false
console.log(test2 instanceof Array); //true
console.log(test3 instanceof Array); //false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With