Failure is part of learning. we should never give up the struggle in life

js 判断数据类型(是数组还是对象)

不能使用tyoeof判断 因为返回值都是object

使用 Object.prototype.toString.call()

该方法的返回值是固定的 [object[[class]]]

每个对象都有一个 内部属性[[class]] 用来表示其类型

但是该属性对于开发者是不可以直接访问的,不过使用Object.prototype.toString.call()可以间接的获取

其值有如下几种:

  • 数组:[[class]]值为 Array
  • 函数:[[class]]值为 Function
  • 数字:[[class]]值为 Number
  • 字符串:[[class]]值为 String
  • 字面量:[[class]]值为 Object

let obj = { name: '张三', age: 18 };
let arr = [1, 2, 3];

console.log(Object.prototype.toString.call(obj));// [object Object]
console.log(Object.prototype.toString.call(arr));//[object Array]

使用instanceof

还是拿上面定义的变量举例子

console.log(obj instanceof Object);// true
console.log(arr instanceof Array);// true

通过原型链

什么你不知道什么事原型链,戳这里(等会补链接哈哈)

好,现在我们知道什么是原型链了,那么我们就理解一下下面的代码

let a = []

其实他是等效于:

let a = new Array()

那么我们就可以打印一下了

console.log(a.__proto__ === Array.prototype);// true

使用 Array.isArray()

注意该方法是 ES6 新增的,如果需要在低版本浏览器中使用,使用 babel 将js转换适配的版本

还是使用上面定义的 a 空数组

console.log(Array.isArray(a));//true

ps:上面方法记得举一反三,动起手来才能知悉问题所在,而后才会得到答案

发表评论

电子邮件地址不会被公开。 必填项已用*标注