Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Identifying Array Object [duplicate]

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

like image 873
Maizere Pathak.Nepal Avatar asked Sep 06 '25 08:09

Maizere Pathak.Nepal


2 Answers

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
}
like image 145
VisioN Avatar answered Sep 09 '25 04:09

VisioN


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
like image 25
LeonardChallis Avatar answered Sep 09 '25 04:09

LeonardChallis