Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

判断JavaScript变量是不是数组 #17

Open
lfb opened this issue Jul 24, 2019 · 0 comments
Open

判断JavaScript变量是不是数组 #17

lfb opened this issue Jul 24, 2019 · 0 comments
Assignees
Labels

Comments

@lfb
Copy link
Owner

lfb commented Jul 24, 2019

各声明一个数组和对象变量

目的为了下面测试

let arr = [1, 2, 3, 4, 5];
let obj = {
    name: 'bobobo'
}

方法一: 使用instanceof方法

instanceof判断原理:通过arr的原型链(__proto__)一层层往上进行查询,能否找到对应的构造函数的原型对象(prototype),如果找到了就返回true,反之false。

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

方法二:使用Array.prototype.isPrototypeOf()方法

利用isPrototypeOf()方法,判定Array是不是在obj的原型链中,如果是,则返回true,否则false。

console.log(Array.prototype.isPrototypeOf(arr)); // true
console.log(Array.prototype.isPrototypeOf(obj)); // false

方法三:使用constructor方法

constructor构造函数指向的是创建它的构造函数。

console.log(arr.constructor === Array); // true
console.log(obj.constructor === Array);  // false

方法四:使用Array.isArray()方法

ES6最新方法

console.log(Array.isArray(arr)); // true
console.log(Array.isArray(obj)); // false

方法五:使用Object.prototype.toString.call()方法(推荐)

使用Object.prototype上的原生toString()方法判断数据类型

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

这里思考为什么不直接使用toString()方法呢?
因为toString为Object的原型方法,而Array ,function等类型作为Object的实例,都重写了toString方法,示例如下:

let array =  [1,2,3];

arr.toString(); // 已经被重写输出:1,2,3 
Object.prototype.toString.call(arr); // 最原始的输出:"[object Array]"

总结

instanceof和constructor有原型链断裂的风险,Object.prototype.toString.call()最稳定。

@lfb lfb self-assigned this Jul 24, 2019
@lfb lfb added the 数组 label Jul 24, 2019
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant