js 中一些意想不到的使用技巧(持續更新,歡迎補充)

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/blogsgit

做者:深予之 (@senntyou)github

版權聲明:自由轉載-非商用-非衍生-保持署名(創意共享3.0許可證數組

相關文章
相關標籤/搜索