- Published on
类型
- Authors

- Name
- 李丹秋
in 和 instanceof的区别
in 是用来判断一个对象的原型链中是否包含响应的属性名称
type Fish = { swim: () => void };
type Bird = { fly: () => void };
function move(animal: Fish | Bird) {
if ("swim" in animal) {
return animal.swim();
}
return animal.fly();
}
instanceof是用来检测一个对象是否属于某一个原型对象的实例。
function logValue(x: Date | string) {
if (x instanceof Date) {
console.log(x.toUTCString());
(parameter) x: Date
} else {
console.log(x.toUpperCase());
(parameter) x: string
}
}
JS IF判读
- 0
- NaN
- "" (the empty string)
- 0n (the bigint version of zero)
- null
- undefined 在js中if判断中以上都代表假值