1. 获取数据类型
Object.prototype.toString.call(value) // 返回value数据的类型
- 数值:返回
[object Number]
。 - 字符串:返回
[object String]
。 - 布尔值:返回
[object Boolean]
。 - undefined:返回
[object Undefined]
。 - null:返回
[object Null]
。 - 数组:返回
[object Array]
。 - arguments 对象:返回
[object Arguments]
。 - 函数:返回
[object Function]
。 - Error 对象:返回
[object Error]
。 - Date 对象:返回
[object Date]
。 - RegExp 对象:返回
[object RegExp]
。 - 其他对象:返回
[object Object]
。
示例:
Object.prototype.toString.call(/aaa/) // "[object RegExp]"
2. 类数组使用Array原型对象上的方法
类数组:含有length属性的对象。本质上所有的类数组都是对象! 原生的类数组(对象)有: 1)arguments 2)document.querySelectorAll('div') 可以使用[...xxx]转数组 自定义的类数组: { length: 1 } 不可以使用[...xxx]
1)将类数组转为数组(slice)
Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 }) // ['a', 'b']
Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 }, 1)
// ['b']
// 另外,还可以使用Array.from()将类数组转数组 Array.from({ 0: 'a', 1: 'b', length: 2 })
// 注意,这种类数组的对象,不能使用[...xxx],因为没有遍历器函数
2)使用数组上的其他方法
function test() { console.log(typeof arguments);// "object" let firstParam = Array.prototype.shift.call(arguments); console.log(firstParam); // 1 } test(1,3)