示例: 使用 Array.isArray() 检查数组
// program to check if an object is an array function checkObject(arr) { // check if arr is array const result = Array.isArray(arr); if(result) { console.log(`[${arr}] is an array.`); } else { console.log(`${arr} is not an array.`); } } const array = [1, 2, 3]; // call the function checkObject(array);
输出
[1,2,3] is an array.
在上面的程序中,
Array.isArray()
方法用于检查对象是否为数组。
如果对象是数组,
Array.isArray()
方法返回
true
,否则返回
false
。
注意: 对于数组,
typeof
运算符返回一个对象。
例如
const arr = [1, 2, 3]; console.log(typeof arr); // object