xxxxxxxxxx
// inside if else check
if(Array.isArray(myVarToTest)) {
// myVatToTest is an array
} else {
// myVarToTest is not an array
}
xxxxxxxxxx
var colors=["red","green","blue"];
if(Array.isArray(colors)){
//colors is an array
}
xxxxxxxxxx
Array.isArray([]) //true
Array.isArray({}) //false
Array.isArray('') //false
Array.isArray(null) //false
xxxxxxxxxx
let fruit = 'apple';
let fruits = ["apple", "banana", "mango", "orange", "grapes"];
const isArray = (arr) => Array.isArray(arr);
console.log(isArray.(fruit)); //output - false
console.log(isArray.(fruits)); //output- true
xxxxxxxxxx
// Check if something is an Array
// just like you do with "typeof"
Array.isArray([1, 2, 3]); // true
Array.isArray('asdf'); // false
xxxxxxxxxx
Method 1: Using the isArray method
Array.isArray(variableName)'
Method 2:
variable instanceof Array
Method 3:
variable.constructor === Array
xxxxxxxxxx
function isArray(value) {
return Object.prototype.toString.call(value) === "[object Array]";
}
xxxxxxxxxx
// npm i is-js-array
const { isJSArray } = require("is-js-array");
isJSArray([]); // true
isJSArray({}); // false
xxxxxxxxxx
if(Object.prototype.toString.call(someVar) === '[object Array]') {
alert('Array!');
}