注意:不能使用typeof
来判断是否为数组,因为它返回的是一个对象
typeof操作符
// 数值
typeof 37 === 'number';
// 字符串
typeof '' === 'string';
// 布尔值
typeof true === 'boolean';
// Symbols
typeof Symbol() === 'symbol';
// Undefined
typeof undefined === 'undefined';
// 对象
typeof {a: 1} === 'object';
typeof [1, 2, 4] === 'object';
// 下面的例子令人迷惑,非常危险,没有用处。避免使用它们。
typeof new Boolean(true) === 'object';
typeof new Number(1) === 'object';
typeof new String('abc') === 'object';
// 函数
typeof function() {} === 'function';
从上面的实例我们可以看出,利用typeof除了array和null判断为object外,其他的都可以正常判断。
使用instanceof操作符 和 对象的constructor 属性
var arr = [1,2,3,1];
console.log(arr instanceof Array); // true
var fun = function(){};
console.log(fun instanceof Function); // true
var arr = [1,2,3,1];
console.log(arr.constructor === Array); // true
var fun = function(){};
console.log(arr.constructor === Function); // true
使用 Object.prototype.toString 来判断是否是数组
Object.prototype.toString.call( [] ) === '[object Array]' // true
Object.prototype.toString.call( function(){} ) === '[object Function]' // true
使用 原型链 来完成判断
[].__proto__ === Array.prototype // true
var fun = function(){}
fun.__proto__ === Function.prototype // true
使用Array.isArray()
Array.isArray([]) // true
ECMAScript5将Array.isArray()正式引入JavaScript,目的就是准确地检测一个值是否为数组。IE9+、 Firefox 4+、Safari 5+、Opera 10.5+和Chrome都实现了这个方法。但是在IE8之前的版本是不支持的。
Array.isArray()这个方法的执行速度比原型链的方式快了近一倍。
将对象转为数组
var obj = {
a: 'xx',
b: 'yy',
c: 'zz'
}
var arr = []
for (let i in obj) {
let o = {};
o[i] = obj[i];
arr.push(o)
}
console.log(arr);
// 打印结果:
[
{a: 'xx'},
{b: 'yy'},
{c: 'zz'}
]