Sunday, 15 May 2016

javascript - Identifying Array Object




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:? what is the reason here?
console.log([].toString()); also outputs
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


Answer



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
}

No comments:

Post a Comment

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...