数值相等比较
JavaScript 提供三种不同的值比较运算: === ——严格相等(三个等号) == ——宽松相等(两个等号)
8种数据类型
前七种为基础数据类型。
Object类型为引用数据类型。
数据类型概念以及存储方式
let a = {
name: "Julia",
age: 20
}
function change(o) {
o.age = 24
o = {
name: "无视",
age: 30
}
return o
}
let b = change(a)
console.log(b.age)
console.log(a.age)
输出
30
24
数据类型检测
typeof
console.log(typeof 1)
console.log(typeof '1')
console.log(typeof undefined)
console.log(typeof true)
console.log(typeof Symbol())
console.log(typeof null)
console.log(typeof [])
console.log(typeof {})
console.log(typeof console)
console.log(typeof console.log)
输出
number
string
undefined
boolean
symbol
object
object
object
object
function
instanceOf
let Car = function () {
}
let benz = new Car()
console.log(benz instanceof Car)
let car = new String("M Benz")
console.log(car instanceof String)
let str = "123"
console.log(str instanceof String)
let int1 = 8
console.log(str instanceof Number)
输出
true
true
false
false
两种方法的优缺点
Object.prototype.toString.call(obj)
检测数据类型的方法
function getType(obj){
let type = typeof obj;
if (type !== 'object'){
return type
}
// 正则中$1表示第一个捕获组
// 在正则表达式中,.表示匹配任意字符(除了换行符),+表示匹配前面的字符1次或多次。而?在这里表示非贪婪匹配,即尽可能少地匹配字符。
// 因此,.+?可以匹配任意字符1次或多次,但是会尽可能少地匹配字符,直到满足后面的条件为止。
return Object.prototype.toString.call(obj).replace(/\[object\s(.+?)]/,'$1');
}
console.log(getType([]))
console.log(getType('123'))
let window = "123"
console.log(getType(window))
console.log(getType(null))
console.log(getType(undefined))
console.log(getType())
console.log(getType(function () {}))
console.log(getType(/123/g))
输出
Array
string
string
Null
undefined
undefined
function
RegExp
强制类型转换
console.log("123" === 123)
console.log("" === null)
console.log("" === 0)
console.log([] === 0)
console.log([] === '')
console.log([] === ![])
console.log(null === undefined)
console.log(Number(null))
console.log(Number(''))
console.log(parseInt(''))
console.log({} + 10)
输出
false
false
false
false
false
false
false
0
0
NaN
[object Object]10
Boolean
隐式类型转换
console.log(null === undefined)
console.log(null === 0)
console.log(null === '')
console.log(0 === '')
console.log('123' === 123)
console.log(0 === false)
console.log(1 === true)
let a = {
value: 0,
valueOf: function () {
this.value++;
return this.value
}
}
console.log(a == 1 && a == 2 && a == 3)
console.log(a === 1 && a === 2 && a === 3)
输出
false
false
false
false
false
false
false
true
false