EN
JavaScript - check if variable is array type
11 points
In this article, we would like to show you how to check if an object or variable is array type using JavaScript.
xxxxxxxxxx
1
console.log(Array.isArray([ ])); // true
2
console.log(Array.isArray(new Array())); // true
3
4
console.log(Array.isArray({ })); // false
5
console.log(Array.isArray(new Object())); // false
6
console.log(Array.isArray(5)); // false
7
console.log(Array.isArray('a')); // false
8
console.log(Array.isArray(true)); // false
9
console.log(Array.isArray(function() { })); // false
10
console.log(Array.isArray(new function() { })); // false
Note: if web browser does not support
Array.isArray
method this approach is useful.
xxxxxxxxxx
1
if (!Array.isArray) {
2
Array.isArray = function(array) {
3
return (array instanceof Array);
4
};
5
}
6
7
// Example:
8
9
console.log(Array.isArray([ ])); // true
10
console.log(Array.isArray(new Array())); // true
11
12
console.log(Array.isArray({ })); // false
13
console.log(Array.isArray(new Object())); // false
14
console.log(Array.isArray(5)); // false
15
console.log(Array.isArray('a')); // false
16
console.log(Array.isArray(true)); // false
17
console.log(Array.isArray(function() { })); // false
18
console.log(Array.isArray(new function() { })); // false
Note: if web browser does not support
Array.isArray
method this approach is useful.
xxxxxxxxxx
1
if (!Array.isArray) {
2
Array.isArray = function(array) {
3
return array.constructor == Array;
4
};
5
}
6
7
// Example:
8
9
console.log(Array.isArray([ ])); // true
10
console.log(Array.isArray(new Array())); // true
11
12
console.log(Array.isArray({ })); // false
13
console.log(Array.isArray(new Object())); // false
14
console.log(Array.isArray(5)); // false
15
console.log(Array.isArray('a')); // false
16
console.log(Array.isArray(true)); // false
17
console.log(Array.isArray(function() { })); // false
18
console.log(Array.isArray(new function() { })); // false
Note: if web browser does not support
Array.isArray
method this approach is useful.
xxxxxxxxxx
1
// Polyfill:
2
3
if (!Array.isArray) {
4
Array.isArray = function(array) {
5
return Object.prototype.toString.call(array) === '[object Array]';
6
};
7
}
8
9
// Example:
10
11
console.log(Array.isArray([ ])); // true
12
console.log(Array.isArray(new Array())); // true
13
14
console.log(Array.isArray({ })); // false
15
console.log(Array.isArray(new Object())); // false
16
console.log(Array.isArray(5)); // false
17
console.log(Array.isArray('a')); // false
18
console.log(Array.isArray(true)); // false
19
console.log(Array.isArray(function() { })); // false
20
console.log(Array.isArray(new function() { })); // false