获取 Array 最后一条数据
1 2 3 4 5 6 7
| const list = [1,2,3,4]
const item1 = list.splice(-1)[0] const item2 = list.pop()
const item3 = list.slice(-1)[0]
|
获取 Array 中指定的对象
1 2 3 4
| const list = [{ id: 1, name: 'Tom'}, { id: 2, name: 'Jerry'}]
const item = list.find(ele => ele.id === 2)[0]
|
判断对象中是否存在该属性
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const obj = { a: 1, b: 2 }
const property1 = obj.hasOwnProperty('a') const property2 = obj.hasOwnProperty('c') const property3 = obj.hasOwnProperty("toString")
Object.prototype.hasOwnProperty.call(obj, 'a')
'a' in obj 'y' in obj 'toString' in obj
|
元素赋值(解构)
1 2 3 4 5 6 7 8 9
|
const [obj, arr, str] = [{}, [], '']
const data = { a: 1, b: 2, c: 3 }
const { a } = data
|
类型转换
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| const [valueString, valueNumber, valueObj] = ['3.14', 123, { a: 1 }]
const number = +valueString const boolean = !!valueString
const str2 = valueNumber + '' const boolean2 = !!valueNumber
const str3 = JSON.stringify(valueObj)
const obj4 = JSON.parse(str3)
|
聚合函数 ??
switch 优化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
const data = { 1: test1, 2: test2, 3: test }
data[something] ?? data[something]()
|
克隆
1 2 3 4 5 6 7 8 9
| const [arr, obj] = [[1, 2, 3], { a: 1 }]
const cloneArr = arr.slice() const cloneObj = { ...obj } const cloneArr = [...arr]
const cloneDeep = JSON.parse(JSON.stringify(obj))
|
按位非运算符(~)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
|
if(~arr.indexOf(item)) {} if(!~arr.indexOf(item)) {}
const float = 1.3
const int = ~~float
|
数组中最大和最小的值
1 2 3 4
| const arr = [1, 2, 3]
Math.max(…arr); Math.min(…arr);
|
参考 https://mp.weixin.qq.com/s/jO7hoh1ffESq8jBfuXZ9Vw