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

数据类型判断 #9

Open
dvlin-dev opened this issue Apr 4, 2022 · 0 comments
Open

数据类型判断 #9

dvlin-dev opened this issue Apr 4, 2022 · 0 comments
Labels
js JavaScript

Comments

@dvlin-dev
Copy link
Owner

dvlin-dev commented Apr 4, 2022

初识

引用数据类型用instaceof,基本数据类型用typeof

instanceof

instanceof 判断 对象的原型链上是否有这个属性,用来判断引用类型
采用递归的方式去原型链上找,直到找到Object.prototype

in : 如果指定的属性在指定的对象或其原型链中,则 in 运算符返回true。
const car = { make: 'Honda', model: 'Accord', year: 1998 };
console.log('make' in car);

function myInstanceof(left, right) {
    //基本数据类型直接返回false
    if(typeof left !== 'object' || left === null) return false;
    //getProtypeOf是Object对象自带的一个方法,能够拿到参数的原型对象
    let proto = Object.getPrototypeOf(left);
    while(true) {
        //查找到尽头,还没找到
        if(proto == null) return false;
        //找到相同的原型对象
        if(proto == right.prototype) return true;
        proto = Object.getPrototypeof(proto);
    }
}

typeof

numer
boolean
string
null
undefined
symbol
bigint

Object.is

=== (en-US) 运算也不相同。 === 运算符 (也包括 == 运算符) 将数字 -0 和 +0 视为相等 ,而将Number.NaNNaN视为不相等.

@dvlin-dev dvlin-dev changed the title instanceof 原理 instanceof typeof Apr 4, 2022
@dvlin-dev dvlin-dev changed the title instanceof typeof 数据类型判断 Apr 4, 2022
@dvlin-dev dvlin-dev added the js JavaScript label Apr 5, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
js JavaScript
Projects
None yet
Development

No branches or pull requests

1 participant