【譯】5分鐘學習 JS 一些小技巧

原文 - Learn these neat JavaScript tricks in less than 5 minutesjavascript

一些平常開發技巧,意譯了。java

清空和截短數組

最簡單的清空和截短數組的方法就是改變 length 屬性:數組

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
複製代碼

使用對象結構模擬命名參數

之前,當咱們但願向一個函數傳遞多個參數時,可能會採用配置對象的模式:less

doSomething({ foo: 'Hello', bar: 'Hey!', baz: 42 });
function doSomething(config) {
  const foo = config.foo !== undefined ? config.foo : 'Hi';
  const bar = config.bar !== undefined ? config.bar : 'Yo!';
  const baz = config.baz !== undefined ? config.baz : 13;
  // ...
}
複製代碼

這是一個古老可是有效的模式,有了 ES2015 的對象結構,你能夠這樣使用:async

function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 }) {
  // ...
}
複製代碼

若是你須要這個配置對象參數變成可選的,也很簡單:函數

function doSomething({ foo = 'Hi', bar = 'Yo!', baz = 13 } = {}) {
  // ...
}
複製代碼

數組的對象解構

使用對象解構將數組項賦值給變量:ui

const csvFileLine = '1997,John Doe,US,john@doe.com,New York';
const { 2: country, 4: state } = csvFileLine.split(',');
複製代碼

注:本例中,2split 以後的數組下標,country 爲指定的變量,值爲 USthis

switch 語句中使用範圍

這是一個在 switch 語句中使用範圍的例子:spa

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;
}
複製代碼

await 多個 async 函數

await 多個 async 函數並等待他們執行完成,咱們能夠使用 Promise.allcode

await Promise.all([anAsyncCall(), thisIsAlsoAsync(), oneMore()])
複製代碼

建立純對象

你能夠建立一個 100% 的純對象,這個對象不會繼承 Object 的任何屬性和方法(好比 constructortoString() 等):

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

格式化 JSON 代碼

JSON.stringify 不只能夠字符串化對象,它也能夠格式化你的 JSON 輸出:

const obj = { 
  foo: { bar: [11, 22, 33, 44], baz: { bing: true, boom: 'Hello' } } 
};

// 第三個參數爲格式化須要的空格數目
JSON.stringify(obj, null, 4); 
// =>"{
// => "foo": {
// => "bar": [
// => 11,
// => 22,
// => 33,
// => 44
// => ],
// => "baz": {
// => "bing": true,
// => "boom": "Hello"
// => }
// => }
// =>}"
複製代碼

移除數組重複項

使用 ES2015 和擴展運算符,你能夠輕鬆移除數組中的重複項:

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

注:只適用於數組內容爲基本數據類型

扁平化多維數組

使用擴展運算符能夠快速扁平化數組:

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]
複製代碼

就這些,但願上面這些優雅的技巧可能幫助你編寫更漂亮的JavaScript

相關文章
相關標籤/搜索