1. 程式人生 > >JS一些 實用竅門

JS一些 實用竅門

1. 刪除陣列尾部元素

const arr = [11, 22, 33, 44, 55, 66];
arr.length = 3;
console.log(arr); //=> [11, 22, 33]
arr.length = 0;
console.log(arr); //=> []
console.log(arr[2]); //=> undefined

2.使用物件解構來處理陣列

可以使用物件解構的語法來獲取陣列的元素:

const csvFileLine = '1997,John Doe,US,[email protected],New York';
const { 2: country, 4: state } = csvFileLine.split(',');

3.在 Switch 語句中使用範圍值

function getWaterState(tempInCelsius) {
  let state;
  switch (true) {
    case (tempInCelsius  0):
      state = 'Solid';
      break;
    case (tempInCelsius > 0 && tempInCelsius <100):
      state = 'Liquid';
      break;
    default:
      state = 'Gas';
  }
  return state;
}

4.await 多個 async 函式

在使用 async/await 的時候,可以使用 Promise.all await 多個 async 函式

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])

5.建立 pure objects

可以建立一個 100% pure object,它不從Object中繼承任何屬性或則方法(比如constructor, toString()等)

const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined

6.格式化 JSON 程式碼

const obj = {
  foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } }
};
// The third parameter is the number of spaces used to
// beautify the JSON output.
JSON.stringify(obj, null, 4);
// =>"{
// =>    "foo": {
// =>        "bar": [
// =>            11,
// =>            22,
// =>            33,
// =>            44
// =>        ],
// =>        "baz": {
// =>            "bing": true,
// =>            "boom": "Hello"
// =>        }
// =>    }
// =>}"

7.從陣列中移除重複元素

const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
//=> [42, "foo", true]

8.平鋪多維陣列

const arr = [11, [22, 33], [44, 55], 66];
const flatArr = [].concat(...arr); //=> [11, 22, 33, 44, 55, 66]

不過上面的方法僅適用於二維陣列,但是通過遞迴,就可以平鋪任意維度的巢狀陣列了:

function flattenArray(arr) {
  const flattened = [].concat(...arr);
  return flattened.some(item => Array.isArray(item)) ?
    flattenArray(flattened) : flattened;
}
const arr = [11, [22, 33], [44, [55, 66, [77, [88]], 99]]];
const flatArr = flattenArray(arr);
//=> [11, 22, 33, 44, 55, 66, 77, 88, 99]