1.对象解构
const { name, age } = { name: '张三', age: 23 };
// 结果: name = '张三', age = 23
2.浅克隆对象
const originalObj = { name: '张三', age: 24 };
const clonedObj = { ...originalObj };
// 结果: clonedObj = { name: '张三', age: 24 }
// 此时改变 clonedObj 的属性,将不会影响到原始对象 originalObj
3.合并对象
const obj1 = { name: '张三' };
const obj2 = { age: 22 };
const mergedObj = { ...obj1, ...obj2 };
// 结果: mergedObj = { name: '张三', age: 22 }
4.清理数组
const arr = [ 0, 1, false, 2, '', 3 ];
const cleanedArray = arr.filter(Boolean);
// 结果: cleanedArray = [1, 2, 3]
5.将 NodeList 转换为数组
const nodesArray = [ ...document.querySelectorAll('div') ];
6.检查数组是否满足指定条件
const arr = [ 1, 2, 3, -5, 4 ];
// 数组中是否有负数
const hasNegativeNumbers = arr.some(num => num < 0);
// 结果: hasNegativeNumbers = true
Array.prototype.some()
函数用于检查数组中是否至少有一个元素,通过所提供的回调函数实现的测试(此处判断是否是负数,返回true
表示通过)
另外,还可以使用Array.prototype.every()
来检查数组的所有元素是否全部通过测试(此处判断是否是正数)
const arr = [ 1, 2, 3, -5, 4 ];
// 数组元素是否全部为正
const allPositive = arr.every(num => num > 0);
// 结果: allPositive = false
7.取两个数组的交集
const arr1 = [1, 2, 3, 4];
const arr2 = [2, 4, 6, 8];
// 取两个数组中公共的元素
const intersection = arr1.filter(value => arr2.includes(value));
// 结果: intersection = [2, 4]
此示例通过使用Array.prototype.filter()
函数去查找arr1
与arr2
中的公共元素。传入的回调函数会检查arr2
是否包含arr1
的每一个元素,从而得到两个数组的交集。
8.将秒数转换为时间格式的字符串
const seconds = 3661; // 一小时是 3600 秒,多出 61 秒
const toTimeString = seconds => new Date(seconds * 1000).toISOString().substr(11, 8);
toTimeString(seconds));
// 结果: '01:01:01'
9.判断对象的值中是否包含有某个值
const person = { name: '张三', age: 30 };
const hasValue = (obj, value) => Object.values(obj).includes(value);
hasValue(person, 30);
// 结果: true
hasValue
函数会检查对象的值中是否存在指定的值。其中Object.values(obj)
用于获取对象中所有的值的数组,然后通过includes(value)
检查指定值是否在该数组中。