- 对数组使用.sort()排序.
错误写法:[1,6,5,11].sort() 排序结果:[1, 11, 5, 6]
正确写法: [1,6,5,11].sort((a,b)=> a-b) - 替换函数
let s = ‘yxy’ const replaced = s.replace(‘y’, ‘o’)
replaced === ‘oxy’ // 只会替换第一个y 且 s的值不会变
若想把所有y都替换, ‘yxy’.replace(/y/g, ‘o’) === ‘oxo’
3.数组不是基础类型
typeof {} === ‘object’ // true
typeof ‘a’ === ‘string’ // true
but typeof [] === ‘object’ // true
若是需要判断一个变量是否是数组,则 Array.isArray(var)
4.Math.min() 比 Math.max() 大; 前者返回 Infinity,后者返回 -Infinity
5. 3<2<1 为 true, 在比较时为 (3<2)<1 => false < 1 true 或者 false 为默认转化为 0 || 1…=> 0 < 1 ==> true
6. 强制要求参数
ES6提供了默认参数值机制,允许你为参数设置默认值,防止在函数被调用时没有传入这些参数。
在下面的例子中,我们写了一个required()函数作为参数a和b的默认值。这意味着如果a或b其中有一个参数没有在调用时传值,会默认required()函数,然后抛出错误。
const required = () => {throw new Error(‘Missing parameter’)};
const add = (a = required(), b = required()) => a + b;
add(1, 2) //3
add(1) // Error: Missing parameter.
-
使用reduce同时实现map和filter
假设现在有一个数列,你希望更新它的每一项(map的功能)然后筛选出一部分(filter的功能)。如果是先使用map然后filter的话,你需要遍历这个数组两次。
在下面的代码中,我们将数列中的值翻倍,然后挑选出那些大于50的数。有注意到我们是如何非常高效地使用reduce来同时完成map和filter方法的吗?const numbers = [10, 20, 30, 40]; const doubledOver50 = numbers.reduce((finalList, num) => { num = num * 2; if (num > 50) { finalList.push(num); } return finalList; }, []); doubledOver50; // [60, 80]
8.删除不需要的属性
let {_internal, tooBig, …cleanObject} = {el1: ‘1’, _internal:“secret”, tooBig:{}, el2: ‘2’, el3: ‘3’};
console.log(cleanObject); // {el1: ‘1’, el2: ‘2’, el3: ‘3’}
9.Sets 数组去重
在ES6中,因为Set只存储唯一值,所以你可以使用Set删除重复项。
let arr = [1, 1, 2, 2, 3, 3];
let deduped = […new Set(arr)] // [1, 2, 3]