// ********** 通过条件判断给变量赋值布尔值 ********** //
let a = 'a'
let b = false
let c = false
//bad
if (a === 'a') {
b = true
} else {
b = false
}
console.log(b) //true
// good
c = a === 'a'
console.log(c) //true
// ********** 判断数组的长度不为0 ********** //
let arr = [1]
// bad
if (arr.length > 0) {
console.log(arr)
}
//good
if (arr.length) {
console.log(arr)
}
if (!arr.length) {
// todo
}
// ********** 三元表达式 ********** //
let d = 'd'
let e = 'e'
let f = false
//bad
if (d === 'd') {
f = d
} else {
f = e
}
console.log(f) //d
// good
f = d === 'd' ? d : e
console.log(f) //d
// ********** 使用includes简化if判断 ********** //
let g = 3
// bad
if (g === 1 || g === 3 || g === 5) {
console.log('包含g')
}
// good
let incArr = [1, 3, 5]
if (incArr.includes(g)) {
console.log('incArr包含a')
}
// ********** 使用some和every方法判断是否有满足条件的数组项 ********** //
let someArr = [1, 3, 5, 7, 9]
//good
let isHasNum = n => someArr.some(num => num === n)
console.log(isHasNum(5)) //true
//best
let isHasNum2 = (n, arr) => arr.some(num => num === n)
console.log(isHasNum2(3, someArr)) //true 数组中只要有一项等于3,即true
let isHasNum3 = (n, arr) => arr.every(num => num < n)
console.log(isHasNum3(10, someArr)) //true 数组中所有项都小于10,即true
// ********** 使用forEach方法遍历修改数组 ********** //
let forEachArr = [{ name: 'a' }, { name: 'b' }]
forEachArr.forEach(item => {
item.key = 'test'
})
console.log(forEachArr) // [{name: 'a', key: 'test'},{name: 'b', key: 'test'}]
// ********** 使用filter形成新数组 ********** //
let filterArr = [1, 2, 3, 4, 5, 6]
let filterArr2 = filterArr.filter(n => n > 3)
console.log(filterArr2) //[4,5,6]
// ********** 使用map ********** //
let mapArr = [1, 2, 3, 4]
let newMapArr = mapArr.map(num => num * 2)
console.log(newMapArr) //[2,4,6,8]
// ********** 使用Object.values和Object.keys方法 ********** //
let obj = {
a: 1,
b: 2,
c: 3
}
let objValues = Object.values(obj)
console.log(objValues) //[1,2,3]
let objKeys = Object.keys(obj)
console.log(objKeys) //['a','b','c']
// ********** 巧用解构数组 ********** //
let a1 = 1
let b2 = 2
let abArr = [a1, b2] = [b2, a1]
console.log(a1, b2) //2,1
// ********** 解构对象 ********** //
let personObj = { full_name: 'Someone', gender: 'male' }
let name = ''
let age = 0
function setForm ({ full_name: name, age = 24 }) {
console.log(name, age) //重构时重命名及默认参数
}
setForm(personObj) //Someone 24
// ********** 箭头函数 ********** //
let arr2 = [1, 2, 3, 4, 5]
let findOddNum = (arr) => arr.filter(num => (num % 2 !== 0))
console.log(findOddNum(arr2)) //返回奇数
// ********** 函数参数校验 ********** //
let studentArr = [18, 19, 20]
let checkoutType = () => {
console.error('参数不能为空')
}
let findStudentByAge = (arr, age = checkoutType()) => arr.filter(item => item === age)
console.log(findStudentByAge(studentArr, 20)) //[20]
console.log(findStudentByAge(studentArr)) //参数不能为空; 对第2个参数校验
网友评论