1、不使用临时变量来交换变量的值
1 2 3 4 5 6 let a = 1 , b = 2 ;[a, b] = [b, a];
2、对象解构,让数据访问更便捷
1 2 3 const { name, age } = { name : '张三' , age : 23 };
3、浅克隆对象
1 2 3 4 5 6 const originalObj = { name : '张三' , age : 24 };const clonedObj = { ...originalObj };
4、合并对象
1 2 3 4 5 6 7 const obj1 = { name : '张三' };const obj2 = { age : 22 };const mergedObj = { ...obj1, ...obj2 };
5、清理数组
1 2 3 4 5 6 const arr = [ 0 , 1 , false , 2 , '' , 3 ];const cleanedArray = arr.filter(Boolean );
6、将 NodeList 转换为数组
1 2 const nodesArray = [ ...document.querySelectorAll('div' ) ];
7、删除数组重复项
1 2 3 4 5 6 const arr = [1 , 2 , 2 , 3 , 4 , 4 , 5 ];const unique = [...new Set (arr)];
8、取两个数组的交集
1 2 3 4 5 6 7 const arr1 = [1 , 2 , 3 , 4 ];const arr2 = [2 , 4 , 6 , 8 ];const intersection = arr1.filter(value => arr2.includes(value));
9、求数组元素的总和
1 2 3 4 5 6 7 const arr = [1 , 2 , 3 , 4 ];const sum = arr.reduce((total, value ) => total + value, 0 );
10、根据指定条件判断,是否给对象的属性赋值
1 2 3 4 5 6 7 const condition = true ;const value = '你好,世界' ;const newObject = {...(condition && {key : value})};
11、使用变量作为对象的键
1 2 3 4 5 6 7 8 const dynamicKey = 'name' ;const value = '张三' ;const obj = {[dynamicKey]: value};
12、离开页面弹出确认对话框
1 2 window .onbeforeunload = () => '你确定要离开吗?' ;
13、对象数组,根据对象的某个key求对应值的总和
1 2 3 4 5 6 7 8 9 const arrayOfObjects = [{x : 1 }, {x : 2 }, {x : 3 }];const sumBy = (arr, key ) => arr.reduce((acc, obj ) => acc + obj[key], 0 );sumBy(arrayOfObjects, 'x' ));
14、将 url 问号后面的查询字符串转为对象
1 2 3 4 5 6 7 const query = 'name=John&age=30' ;const parseQuery = query => Object .fromEntries(new URLSearchParams(query));
15、求某对象所有属性值的最大值
1 2 3 4 5 6 7 8 9 10 const scores = { math : 95 , chinese : 99 , english : 88 };const maxObjectValue = obj => Math .max(...Object.values(obj));maxObjectValue(scores));
16、判断对象的值中是否包含有某个值
1 2 3 4 5 6 7 const person = { name : '张三' , age : 30 };const hasValue = (obj, value ) => Object .values(obj).includes(value);hasValue(person, 30 );
17、安全访问深度嵌套的对象属性
1 2 3 4 5 6 7 8 9 10 11 12 13 const user = { profile : { name : '张三' } };const userName = user.profile?.name ?? '匿名' ;
18、条件执行语句
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 const isEligible = true ;isEligible && performAction(); const isEligible = true ;let value = '' ;isEligible && (value = '条件达成' );
19、切换元素的 class
1 2 3 4 5 6 const element = document .querySelector('.my-element' );const toggleClass = (el, className ) => el.classList.toggle(className);toggleClass(element, 'active' );
20、检查对象是否为空
1 2 3 const isEmptyObject = obj => Object .keys(obj).length === 0 ;isEmptyObject({}) isEmptyObject({ name : 'John' })
21、滚动到页面顶部
1 2 const goToTop = () => window .scrollTo(0 , 0 )goToTop()
22、