We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
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
目的为了下面测试
let arr = [1, 2, 3, 4, 5]; let obj = { name: 'bobobo' }
instanceof判断原理:通过arr的原型链(__proto__)一层层往上进行查询,能否找到对应的构造函数的原型对象(prototype),如果找到了就返回true,反之false。
console.log(arr instanceof Array); // true console.log(obj instanceof Array); // false
利用isPrototypeOf()方法,判定Array是不是在obj的原型链中,如果是,则返回true,否则false。
console.log(Array.prototype.isPrototypeOf(arr)); // true console.log(Array.prototype.isPrototypeOf(obj)); // false
constructor构造函数指向的是创建它的构造函数。
console.log(arr.constructor === Array); // true console.log(obj.constructor === Array); // false
ES6最新方法
console.log(Array.isArray(arr)); // true console.log(Array.isArray(obj)); // false
使用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()最稳定。
The text was updated successfully, but these errors were encountered:
lfb
No branches or pull requests
各声明一个数组和对象变量
目的为了下面测试
方法一: 使用instanceof方法
instanceof判断原理:通过arr的原型链(__proto__)一层层往上进行查询,能否找到对应的构造函数的原型对象(prototype),如果找到了就返回true,反之false。
方法二:使用Array.prototype.isPrototypeOf()方法
利用isPrototypeOf()方法,判定Array是不是在obj的原型链中,如果是,则返回true,否则false。
方法三:使用constructor方法
constructor构造函数指向的是创建它的构造函数。
方法四:使用Array.isArray()方法
ES6最新方法
方法五:使用Object.prototype.toString.call()方法(推荐)
使用Object.prototype上的原生toString()方法判断数据类型
这里思考为什么不直接使用toString()方法呢?
因为toString为Object的原型方法,而Array ,function等类型作为Object的实例,都重写了toString方法,示例如下:
总结
instanceof和constructor有原型链断裂的风险,Object.prototype.toString.call()最稳定。
The text was updated successfully, but these errors were encountered: