Thank you Dang Dang for the post. jQuery, $.isArray() uses Array.isArray() JavaScript method. But it is not supported by older browsers.
simply using $.isArray()
Since a JavaScript Array is an object, typeof operator will return object for an array. So we cannot use that in this case.We can use Array.isArray() in browsers that support ECMAScript 5.Array.isArray(myArray); // returns trueBut older versions of browsers doesn't support ECMAScript 5. So, you need to write your own function for this. You can check the prototype of the object to search for the word "Array".function isArray(myVar) {return myVar.constructor.toString().indexOf("Array") > -1; }The above function will return true if the parameter is an array.
using $.isArray()
Two ways to check if an Array
Code Samples Below:
const programmingLanguages = ['C#', 'JavaScript', 'Java'];//old wayconsole.log(Object.prototype.toString.call(programmingLanguages) === '[object Array]'); //output: true//new wayconsole.log(Array.isArray(programmingLanguages)); //output: true
const programmingLanguages = ['C#', 'JavaScript', 'Java'];
//old way
console.log(Object.prototype.toString.call(programmingLanguages) === '[object Array]'); //output: true
//new way
console.log(Array.isArray(programmingLanguages)); //output: true
To check if object you can use the typeof operator and check if it is not equal to null. The reason you need to check if not null is because null when passed into the typeof operator returns an “object” result.
const customer = {};console.log(typeof(customer)); //output: object; //but it is better to check if typeof object and not nullconsole.log(typeof(customer) === "object" && customer !== null); //output: trueconst product = null;//but it is better to check if typeof object and not equal to nullconsole.log(typeof(product) === "object" && product !==null); //output: false
const customer = {};
console.log(typeof(customer)); //output: object;
//but it is better to check if typeof object and not null
console.log(typeof(customer) === "object" && customer !== null); //output: true
const product = null;
//but it is better to check if typeof object and not equal to null
console.log(typeof(product) === "object" && product !==null); //output: false
$.isArray()
let obj ={}; let arr = [];check output of console.log in each variable and you can see that they have different proto.console.log(obj.constructor.prototype.hasOwnProperty('push')); // this will give false because and object don't have a push method where as an array have the push method. console.log(arr.constructor.prototype.hasOwnProperty('push')); // will return true