散记

57 阅读2分钟

类型判断

typeof

判断一些简单类型(string、number、boolean)还行

typeof [] // 'object'
typeof {} // 'object'
typeof new Map() // 'object'
typeof new Date() // 'object'
typeof new Set() // 'object'

Object.prototype.toString

完美判断数据类型

typeof [] // '[object Array]'
typeof {} // '[object Object]'
new Map() // '[object Map]'
new Date() // '[object Date]'
new Set() // '[object Set]'

isNaN

会尝试将参数转换为数值,如果能成功转换则返回false,否则返回true;

判断非数字
isNaN(NaN)  // true
isNaN(undefined) // true
isNaN('123')  // false
isNaN(123)    // false
isNaN(true)   // false

Number.isNaN()

严格判断NaN

Number.isNaN(NaN) // true

instanceof

运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上

function C () {}
var o = new C()
console.log(o instanceof C) // C在o的原型链上。

Array.isArray

判断是否是数组

检测属性是否存在方法

in 运算符

指定的属性在指定的对象或其原型链中

const car = { make: 'Honda', model: 'Accord', year: 1998 }

console.log('make' in car)
// Expected output: true

delete car.make
if ('make' in car === false) {
  car.make = 'Suzuki'
}

console.log(car.make) // Expected output: "Suzuki"

console.log('toString' in {} //true)

Reflect.has()

静态方法 Reflect.has() 作用与 in 操作符相同。

  • 返回值:boolean
  • 参数1:对象
  • 参数2: 属性
Reflect.has({ x: 0 }, 'x') // true
Reflect.has({ x: 0 }, 'y') // false

// 如果该属性存在于原型链中,返回 true
Reflect.has({ x: 0 }, 'toString')

Object.hasOwn

检测是否为自由属性(非继承)

  • 返回值:boolean
  • 参数1:对象
  • 参数2:检测的属性
Reflect.has({ x: 0 }, 'x') // true
Reflect.has({ x: 0 }, 'y') // false

// 如果该属性存在于原型链中,返回 false
Reflect.has({ x: 0 }, 'toString')

this指向

call

改变this指向,传序列,立即执行

function demo(...rest){
    this.push(...rest)
    //this = arr = [1,2,3,4,5]
}
let arr = []
demo.call(arr,1,2,3,4,5)  // 调用方法

bind

改变this指向,传序列,非立即执行

function demo(...rest){
    this.push(...rest)
    //this = arr = [1,2,3,4,5]
}
let arr = []
demo.bind(arr,1,2,3,4,5) // 不会调用方法

apply

改变this指向,传数组,立即执行

function demo(rest){
    this.push(...rest)
    //this = arr = [1,2,3,4,5]
}
let arr = []
demo.bind(arr,[1,2,3,4,5]) // 不会调用方法

数组方法

indexOf

获取索引,有责返回索引值,没有就-1

splice

截取一个新数组,不改变原数组 参数:

  • 参数1:起始索引值
  • 参数2:个数

new Array

生成一个新数组

fill

对数组进行填充

concat

合并数组

reduce

累计

join

替换分隔符,转成string类型

every

判断所有项是否都符合条件

对象方法

Object.freeze

冻结对象,浅冻结,第一层不可修改

Object.create

创建新对象

Object.keys

获取对象的所有key值,返回一个数组

字符串方法

slice

截取

split

转数组

String

转字符串

  • 能转的就会直接转
  • 不能的会被转成类型
String(0) //'0' 
String(null) //'null' 
String(undefined) //'undefined' 
String(new Map()) //'[object Map]'

toLowerCase

转小写

toUpperCase

转大写

replace

替换

charAt

获取字符串中某个项,默认为0

let str = 'abc'
str.charAt() // 'a' 
str.charAt(1) // 'b' 

数字方法

parseFloat Math.floor

日期 getTime

数据类型转换

JSON.stringify toString

其他

正则 || & ?:; obj[a] (对象通过变量取值) arguments 闭包 递归