类型判断与转换
JavaScript 中类型判断与转换
类型/ 格式判断与转换
typeof
数值、字符串、布尔值分别返回
typeof 123; // "number"
typeof "123"; // "string"
typeof false; // "boolean"
函数返回
// 定义一个空函数
function f(){}
typeof f
// "function"
( 3)undefined
typeof undefined
// "undefined"
利用这一点,
v
// ReferenceError: v is not defined
typeof v
// "undefined"
实际编程中,这个特点通常用在判断语句。
// 错误的写法
if (v){
// ...
}
// ReferenceError: v is not defined
// 正确的写法
if (typeof v === "undefined"){
// ...
}
除此以外,都返回
typeof window // "object"
typeof {} // "object"
typeof [] // "object"
typeof null // "object"
从上面代码可以看到,空数组
instanceof
const o = {};
const a = [];
o instanceof Array; // false
a instanceof Array; // true
类型的自动转换
当遇到以下几种情况,
- 不同类型的数据进行互相运算;
- 对非布尔值类型的数据求布尔值
; - 对非数值类型的数据使用一元运算符
( 即 “+” 和 “-”)。
动态类型检查
tcomb
npm install tcomb --save
A type-checked function:
import t from 'tcomb';
function sum(a, b) {
t.Number(a);
t.Number(b);
return a + b;
}
sum(1, 's'); // throws '[tcomb] Invalid value "s" supplied to Number'
A user defined type:
const Integer = t.refinement(t.Number, (n) => n % 1 === 0, 'Integer');
A type-checked class:
const Person = t.struct({
name: t.String, // required string
surname: t.maybe(t.String), // optional string
age: Integer, // required integer
tags: t.list(t.String) // a list of strings
}, 'Person');
// methods are defined as usual
Person.prototype.getFullName = function () {
return `${this.name} ${this.surname}`;
};
const person = Person({
surname: 'Canti'
}); // throws '[tcomb] Invalid value undefined supplied to Person/name: String'
类型判断
typeof
const s = 'hello';
console.log(typeof(s))//String
以下是我在
从这张表格可以看出,数组被归到了
const a = null;
const b = {};
const c= [];
console.log(typeof(a)); //Object
console.log(typeof(b)); //Object
console.log(typeof(c)); //Object
运行上面的代码就会发现,在参数为数组,对象或者
instanceof
既然
object instanceof constructor
用我的理解来说,就是要判断一个
const a = [];
const b = {};
console.log(a instanceof Array);//true
console.log(a instanceof Object);//true,在数组的原型链上也能找到Object构造函数
console.log(b instanceof Array);//false
由上面的几行代码可以看出,使用
constructor
实例化的数组拥有一个
toString
另一个行之有效的方法就是使用
如果一个对象的
你可能会纠结,为什么不是直接调用数组,或则字符串自己的的
const a = ['Hello','Howard'];
const b = {0:'Hello',1:'Howard'};
const c = 'Hello Howard';
a.toString();//"Hello,Howard"
b.toString();//"[object Object]"
c.toString();//"Hello,Howard"
从上面的代码可以看出,除了对象之外,其他的数据类型的
const a = ['Hello','Howard'];
const b = {0:'Hello',1:'Howard'};
const c = 'Hello Howard';
Object.prototype.toString.call(a);//"[object Array]"
Object.prototype.toString.call(b);//"[object Object]"
Object.prototype.toString.call(c);//"[object String]"
使用
const a = ["Hello", "Howard"];
const b = { 0: "Hello", 1: "Howard" };
const c = "Hello Howard";
Object.prototype.toString.apply(a); //"[object Array]"
Object.prototype.toString.apply(b); //"[object Object]"
Object.prototype.toString.apply(c); //"[object String]"
总结一下,我们就可以用写一个方法来判断数组是否为数组:
const isArray = (something)=>{
return Object.prototype.toString.call(something) === '[object Array]';
}
cosnt a = [];
const b = {};
isArray(a);//true
isArray(b);//false
但是,如果你非要在创建这个方法之前这么来一下,改变了
//重写了toString方法
Object.prototype.toString = () => {
alert("你吃过了么?");
};
//调用String方法
const a = [];
Object.prototype.toString.call(a); //弹框问你吃过饭没有
当然了,只有在浏览器当中才能看到
属性判断
obj.prop !== undefined: compare against undefined directly typeof obj.prop !== ‘undefined’: verify the property value type obj.hasOwnProperty(‘prop’): verify whether the object has an own property ‘prop’ in obj: verify whether the object has an own or inherited property
隐式类型转换
在console.log
操作常常会将任何值都转化为字符串然后展示,而数学运算则会首先将值转化为数值类型
我们首先来看几组典型的
// 比较
[] == ![] // true
NaN !== NaN // true
1 == true // true
2 == true // false
"2" == true // flase
null > 0 // false
null < 0 // false
null == 0 // false
null >= 0 // true
// 加法
true + 1 // 1
undefined + 1 // NaN
let obj = {};
{} + 1 // 1,这里的 {} 被当成了代码块
{ 1 + 1 } + 1 // 1
obj + 1 // [object Object]1
{} + {} // Chrome 上显示 "[object Object][object Object]",Firefox 显示 NaN
[] + {} // [object Object]
[] + a // [object Object]
+ [] // 等价于 + "" => 0
{} + [] // 0
a + [] // [object Object]
[2,3] + [1,2] // '2,31,2'
[2] + 1 // '21'
[2] + (-1) // "2-1"
// 减法或其他操作,无法进行字符串连接,因此在错误的字符串格式下返回 NaN
[2] - 1 // 1
[2,3] - 1 // NaN
{} - 1 // -1
原始类型间转换
// String
let value = true;
console.log(typeof value); // boolean
value = String(value); // now value is a string "true"
console.log(typeof value); // string
// Number
let str = "123";
console.log(typeof str); // string
let num = Number(str); // becomes a number 123
console.log(typeof num); // number
let age = Number("an arbitrary string instead of a number");
console.log(age); // NaN, conversion failed
// Boolean
console.log(Boolean(1)); // true
console.log(Boolean(0)); // false
console.log(Boolean("hello")); // true
console.log(Boolean("")); // false
最终,我们可以得到如下的
原始值 | 转化为数值类型 | 转化为字符串类型 | 转化为 |
---|---|---|---|
false | 0 | “false” | false |
true | 1 | “true” | true |
0 | 0 | “0” | false |
1 | 1 | “1” | true |
“0” | 0 | “0” | true |
“1” | 1 | “1” | true |
NaN | NaN | “NaN” | false |
Infinity | Infinity | “Infinity” | true |
-Infinity | -Infinity | “-Infinity” | true |
"” | 0 | "" | false |
“20” | 20 | “20” | true |
“twenty” | NaN | “twenty” | true |
[ ] | 0 | "" | true |
[20] | 20 | “20” | true |
[10,20] | NaN | “10,20” | true |
[“twenty”] | NaN | “twenty” | true |
[“ten”,“twenty”] | NaN | “ten,twenty” | true |
function(){} | NaN | “function(){}” | true |
{ } | NaN | “[object Object]” | true |
null | 0 | “null” | false |
undefined | NaN | “undefined” | false |
更多比较表格参考 JavaScript-Equality-Table。
ToPrimitive
在比较运算与加法运算中,都会涉及到将运算符两侧的操作对象转化为原始对象的步骤;而alert
函数、数学运算符、作为对象的键都是典型场景,该函数的签名如下:
ToPrimitive(input, PreferredType?)
为了更好地理解其工作原理,我们可以用
const ToPrimitive = function (obj, preferredType) {
const APIs = {
typeOf: function (obj) {
return Object.prototype.toString.call(obj).slice(8, -1);
},
isPrimitive: function (obj) {
const _this = this,
types = ["Null", "Undefined", "String", "Boolean", "Number"];
return types.indexOf(_this.typeOf(obj)) !== -1;
},
}; // 如果 obj 本身已经是原始对象,则直接返回
if (APIs.isPrimitive(obj)) {
return obj;
} // 对于 Date 类型,会优先使用其 toString 方法;否则优先使用 valueOf 方法
preferredType =
preferredType === "String" || APIs.typeOf(obj) === "Date"
? "String"
: "Number";
if (preferredType === "Number") {
if (APIs.isPrimitive(obj.valueOf())) {
return obj.valueOf();
}
if (APIs.isPrimitive(obj.toString())) {
return obj.toString();
}
} else {
if (APIs.isPrimitive(obj.toString())) {
return obj.toString();
}
if (APIs.isPrimitive(obj.valueOf())) {
return obj.valueOf();
}
}
throw new TypeError("TypeError");
};
我们可以简单覆写某个对象的
let obj = {
valueOf: () => {
return 0;
},
};
obj + 1; // 1
如果我们强制将某个对象的 valueOf
与 toString
方法都覆写为返回值为对象的方法,则会直接抛出异常。
obj = {
valueOf: function () {
console.log("valueOf");
return {}; // not a primitive
},
toString: function () {
console.log("toString");
return {}; // not a primitive
}
}
obj + 1
// error
Uncaught TypeError: Cannot convert object to primitive value
at <anonymous>:1:5
值得一提的是对于数值类型的 valueOf()
函数的调用结果仍为数组,因此数组类型的隐式类型转换结果是字符串。而在
- 当
obj[Symbol.toPrimitive](preferredType)
方法存在时,优先调用该方法; - 如果
preferredType 参数为String ,则依次尝试obj.toString()
与obj.valueOf()
; - 如果
preferredType 参数为Number 或者默认值,则依次尝试obj.valueOf()
与obj.toString()
。
而
obj[Symbol.toPrimitive] = function(hint) {
// return a primitive value
// hint = one of "string", "number", "default"
}
我们同样可以通过覆写该方法来修改对象的运算表现:
user = {
name: "John",
money: 1000,
[Symbol.toPrimitive](hint) {
console.log(`hint: ${hint}`);
return hint == "string" ? `{name: "${this.name}"}` : this.money;
},
};
// conversions demo:
console.log(user); // hint: string -> {name: "John"}
console.log(+user); // hint: number -> 1000
console.log(user + 500); // hint: default -> 1500
比较运算
标准的相等性操作符
- 如果
x 或y 中有一个为NaN ,则返回false ; - 如果
x 与y 皆为null 或undefined 中的一种类型,则返回true(null == undefined // true ) ;否则返回false(null == 0 // false ) ; - 如果
x,y 类型不一致,且x,y 为String 、Number、Boolean 中的某一类型,则将x,y 使用toNumber 函数转化为Number 类型再进行比较; - 如果
x ,y 中有一个为Object ,则首先使用ToPrimitive 函数将其转化为原始类型,再进行比较。 - 如果
x ,y 皆为Object ,则进行Reference 比较;譬如[] ==
我们再来回顾下文首提出的 [] == ![]
这个比较运算,首先 []
为对象,则调用""
;对于右侧的 ![]
,首先会进行显式类型转换,将其转化为null >= 0
为<
为>=
为
加法运算
对于加法运算而言,
prim1 := ToPrimitive(value1)
prim2 := ToPrimitive(value2)
这里将会优先调用除了valueOf
方法,而因为数组的 valueOf
方法的返回值仍为数组类型,则会返回其字符串表示。而经过转换之后的