# js 中一些意想不到的使用技巧(持续更新,欢迎补充) ### 1. 箭头函数 `=>` 返回 `map` 对象 ``` // 一般的写法 const makeMap = () => { return {key: 'value'}; }; // 简洁的写法 const makeMap = () => ({key: 'value'}); ``` ### 2. 对象属性名不确定,需要动态的传入 ``` // 一般的写法 const makeMap = (key, value) => { const obj = {}; obj[key] = value; return obj; }; // 简洁的写法 const makeMap = (key, value) => ({[key]: value}); ``` ### 3. 复制一个对象,并重写其中的一些属性 ``` const source = {hello: 'hello', hi: 'hi'}; // 一般的写法 const target = Object.assign({}, source); target.hello = 'hello everyone'; // 简洁的写法 const target = {...source, hello: 'hello everyone'}; ``` ### 4. 数组解构为函数参数 ``` const arr = [1, 2, 3]; const plus = (...args) => args.reduce((a, b) => a + b); // 一般的写法 plus(arr[0], arr[1], arr[2], 4, 5); // 简洁的写法 plus(...arr, 4, 5); ``` ### 5. 向一个数组添加另一数组的所有元素 ``` const arr1 = [1, 2, 3]; const arr2 = [4, 5, 6]; // 一般的写法 arr1 = arr1.concat(arr2); // 简洁的写法 arr1.push(...arr2); ``` ### 6. 回调函数简写 ``` // 一般的写法 promise.catch(e => { console.log(e); }); // 简洁的写法 promise.catch(console.log); ``` ### 7. 多级箭头函数 `=>` ``` // 一般的写法 const makeTimesFunc = times => { return value => { return value * times; }; }; // 简洁的写法 const makeTimesFunc = times => value => value * times; ``` ### 8. 从右向左函数复式调用 ``` // 不确定元素个数,举例 3 个 const fnCollection = [str => `${str} | fisrt`, str => `${str} | second`, str => `${str} | third`]; // 一般的写法 const addManySuffixes = str => { let result = str; for(let i = fnCollection.length - 1; i > -1; i -= 1) result = fnCollection[i](result); return result; }; // 简洁的写法 const addManySuffixes = fnCollection.reduce((a, b) => str => a(b(str))); // 可以把 str 参数扩展成任意参数 const addManySuffixes = fnCollection.reduce((a, b) => (...args) => a(b(...args))); ``` ## 后续 更多博客,查看 [https://github.com/senntyou/blogs](https://github.com/senntyou/blogs) 作者:[深予之 (@senntyou)](https://github.com/senntyou) 版权声明:自由转载-非商用-非衍生-保持署名([创意共享 3.0 许可证](https://creativecommons.org/licenses/by-nc-nd/3.0/deed.zh))