JavaScript
- 七种内置数据类型null,undefined,boolean,number,string,object,symbol
- object类型function,array,date等
使用typeof判断数据类型
console.log(typeof 5);
console.log(typeof 'lucus');
console.log(typeof undefined);
console.log(typeof true);
console.log(typeof null);
- 使用typedef可以判断除null其他基本数据类型,function,symbol,null会被判断为null
手写instanceof
const instancdofMock = (L, R) => {
if (typeof L !== 'object') {
return false
}
while (true) {
if (L == null) {
return false
}
if (R.prototype === L.__proto__) {
return true
}
L = L.__proto__
}
}
console.log(instancdofMock('', String))
function Person(name) {
this.name = name
}
const p = new Person('lucus')
console.log(instancdofMock(p, Person))
使用constructor和Object.prototype.toString判断数据类型(万能方法、终极方法)
console.log(Object.prototype.toString.call('lucas'))
console.log(Object.prototype.toString.call(undefined))
console.log(Object.prototype.toString.call(true))
console.log(Object.prototype.toString.call({}))
console.log(Object.prototype.toString.call([]))
console.log(Object.prototype.toString.call(function() {}))
console.log(Object.prototype.toString.call(null))
console.log(Object.prototype.toString.call(Symbol('lucas')))
- constructor 如果尝试读取其constructor属性就会报错,其他不会
var foo = true
console.log(foo.constructor)
类型转换
- 当使用+运算符计算string类型个其他类型数据类型相加时,其他数据类型都会转换为string类型,而在其他情况下,都会转换为number 类型,但是undefined 会转换为NaN
console.log(1 + '1')
console.log(1 + false)
console.log(1 + true)
console.log(1 + undefined)
console.log('lucas' + true)
- 对象类型转换的时候,会先调用valueOf,再调用toString
- 重写valueOf和toString
const foo = {
toString(){
return 'lucus'
},
valueOf(){
return 1
}
}
- 如果+两边都是字符串就进行拼接操作
- 如果只有一边是字符串,则将其他值转换为字符串
- 如果有一边是对象,则调用valueOf或toString方法取得值,将其转换为基本数据类型再拼接
函数传递参数
- 函数参数为基本数据类型时,函数体内复制了一份参数值,任何操作都不会影响原参数的实际值
- 函数参数是引用类型的时候,当在函数体内修改这个值的某个属性时,将会对原来的参数进行修改
- 函数参数是引用类型的时候,如果直接修改这个值的引用地址,则相当于在函数体内创建了一个引用,任何操作都不会影响原参数的实际值
const obj = {
user: {
posts: [
{ title: 'Foo', comments: [ 'Good one!', 'Interesting...' ] },
{ title: 'Bar', comments: [ 'Ok' ] },
{ title: 'Baz', comments: []}
],
comments: []
}
}
var result
tyr {
result = obk.user.posts[0].comments
}catch {
result = null
}