20个不容错过的ES6技巧

作者: jie 分类: JavaScript 发布时间: 2023-06-13 10:50

整理了20个使用频率很高的ES6代码块

1. 打乱数组顺序

let arr = ['a', 67, true, false, '55']
arr = arr.sort(() => 0.5 - Math.random())
console.log(arr)
//['a', false, 67, '55', true]

2. 去除数字之外的所有字符

const str = 'xieyezi 23213 is 95994 so hansome 223333'
const numbers = str.replace(/\D/g, '')
console.log(numbers)
//2321395994223333

3. 反转字符串或者单词

const sentence = 'xieyezi js so handsome, lol.'
const reverseSentence = reverseBySeparator(sentence, "")
console.log(reverseSentence)
//.lol ,emosdnah os sj izeyeix

const reverseEachWord = reverseBySeparator(reverseSentence, " ")
console.log(reverseEachWord)
//izeyeix sj os ,emosdnah .lol

function reverseBySeparator(string, separator) {
	return string.split(separator).reverse().join(separator)
}

4. 将十进制转换为二进制或十六进制

const num = 43
const binaryNum = num.toString(2)
const hexadecimalNum = num.toString(16)

console.log(binaryNum)
//101011
console.log(hexadecimalNum)
//2b

5. 合并多个对象

const city = {
	name: 'chongqing',
	population: '2000000',
}
const location = {
	longitude: '106.55',
	latitude: '29.56',
}
const fullCity = {
	...city,
	...location
}
console.log(fullCity)

// {
//   name: 'chongqing',
//   population: '2000000',
//   longitude: '106.55',
//   latitude: '29.56'
// }

6. === 和 == 的区别

// == -> 类型转换(浅比较)
// === -> 无类型转换(严格比较)

0 == false //true
0 === false //false
1 == '1' //true
1 === '1' //false
null == undefined //true
null === undefined //false

7. 解构赋值

const forest = {
	location: 'Sweden',
	animals: 3,
	animalsTypes: ['Lions', 'Tigers', 'Bears'],
}
const {
	location,
	animals,
	animalsTypes
} = forest
const [lions, tigers, bears] = animalsTypes

console.log(location) // Sweden
console.log(animals) // 3
console.log(lions) // Lions
console.log(tigers) // Tigers
console.log(bears) // Bears

8. 交换变量的值

let bears = 'bears'
let tigers = 'tigers';
[bears, tigers] = [tigers, bears]
console.log(bears) // tigers
console.log(tigers) // bears

9-1. 判断回文字符串

const isRevervse = (str1, str2) => {
	const normalize = (str) =>
		str.toLowerCase()
		.normalize('NFD')
		.split('')
		.reverse()
		.join('')
	return normalize(str1) === str2
}

console.log(isRevervse('anagram', 'margana')) // true
console.log(isRevervse('rac', 'cra')) // false

回文字符串: 正着写和反着写都一样的字符串

9-2. 判断两个字符串是否为互相排列

const isAnagram = (str1, str2) => {
	const normalize = (str) =>
		str.toLowerCase()
		.normalize('NFD')
		.split('')
		.sort()
		.join('')
	return normalize(str1) === normalize(str2)
}

console.log(isAnagram('anagram', 'nagaram')) // true
console.log(isAnagram('rat', 'car')) // false
console.log(isAnagram('heArt', 'traEH')) // true

判断两个字符串是否为互相排列: 给定两个字符串,一个是否是另一个的排列

10. 可选链操作符

const player = {
	name: 'xieyezi',
	rating: 1000,
	click: () => {
		return 'click'
	},
	pass: (teammate) => {
		return `Pass to ${teammate}`
	},
}

console.log(player?.name) // xieyezi
console.log(player?.click?.()) // click
console.log(player?.teammate?.()) //undefined

MDN: 可选链操作符( ?. )允许读取位于连接对象链深处的属性的值,而不必明确验证链中的每个引用是否有效。?. 操作符的功能类似于 . 链式操作符,不同之处在于,在引用为空(nullish ) (null 或者 undefined) 的情况下不会引起错误,该表达式短路返回值是 undefined。与函数调用一起使用时,如果给定的函数不存在,则返回 undefined

例如:

if (res && res.data && res.data.success) {   
   //code
} 

相当于:

if (res?.data?.success) {
  // code
}

11. 三目运算符

// condition ? expression if true : exrpession if false
const oxygen = 10
const diver = (oxygen < 10) ? 'Low oxygen' : 'High oxygen'
console.log(diver) // High oxygen

12. 从数组中随机选择一个值

const elements = [24, 'you', 777, 'breaking', 99, 'full']
const random = (arr) => arr[Math.floor(Math.random() * arr.length)]
const randomElement = random(elements)
console.log(randomElement) // 99

13. 冻结对象

const octopus = {
	tentacles: 8,
	color: 'blue',
}
Object.freeze(octopus)
octopus.tentacles = 10 // Error,不会改变
console.log(octopus) // { tentacles: 8, color: 'blue' }

14. 删除数组重复的元素

const animals = ['bears', 'lions', 'tigers', 'bears', 'lions']
const unique = (arr) => [...new Set(arr)]
console.log(unique(animals)) // [ 'bears', 'lions', 'tigers' ]

15. 保留指定位小数

const num = 0.1233456789
const fixed2 = num.toFixed(2)
const fixed3 = num.toFixed(3)

console.log(fixed2) // 0.12
console.log(fixed3) // 0.123

16. 清空数组

const numbers = [1, 2, 3, 4, 5]
numbers.length = 0

console.log(numbers) // []

17. 从 RGB 转换为 HEX

const rgbToHex = (r, g, b) => {
	const toHex = (num) => {
		const hex = num.toString(16)
		return hex.length === 1 ? `0${hex}` : hex
	}
	return `#${toHex(r)}${toHex(g)}${toHex(b)}`
}
console.log(rgbToHex(46, 32, 67)) // #2e2043

18. 从数组中获取最大值和最小值

const nums = [1, 2, 3, 4, 5, -3, 99, -45, -1]
const max = Math.max(...nums)
const min = Math.min(...nums)
console.log(max) // 99
console.log(min) // -45

19. 空值合并运算符

const nullval = null
const emptyString = ''
const someNum = 13

const a = nullval ?? 'A default'
const b = emptyString ?? 'B default'
const c = someNum ?? 'C default'

console.log(a) // A default
console.log(b) // '' // empty string 不等于 undefined or null
console.log(c) // 13

MDN: 空值合并操作符??)是一个逻辑操作符,当左侧的操作数为 null 或者 undefined 时,返回其右侧操作数,否则返回左侧操作数。

20. 过滤数组中值为 false 的值

const nums = [1, 0, undefined, null, false]
const truthyNums = nums.filter(Boolean)
console.log(truthyNums) // [1]

发表回复