5 分鐘掌握 JavaScript 實用竅門

一開始 JavaScript 只是爲網頁增添一些實時動畫效果,如今 JS 已經能作到先後端通吃了,並且仍是年度流行語言。本文分享幾則 JS 小竅門,可讓你事半功倍 ~css

1. 刪除數組尾部元素

一個簡單方法就是改變數組的length值:html

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

複製代碼

2. 使用對象解構(object destructuring)來模擬命名參數

若是須要將一系列可選項做爲參數傳入函數,你極可能會使用對象(Object)來定義配置(Config)。前端

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;
  // ...
}

複製代碼

不過這是一個比較老的方法了,它模擬了 JavaScript 中的命名參數。web

在 ES 2015 中,你能夠直接使用對象解構:後端

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

複製代碼

讓參數可選也很簡單:設計模式

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

複製代碼

3. 使用對象解構來處理數組

可使用對象解構的語法來獲取數組的元素:數組

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

複製代碼

這裏推薦一下個人前端學習交流圈:784783012,裏面都是學習前端的,從最基礎的HTML+CSS+JS【炫酷特效,遊戲,插件封裝,設計模式】到移動端HTML5的項目實戰的學習資料都有整理,送給每一位前端小夥伴,有想學習web前端的,或是轉行,或是大學生,還有工做中想提高本身能力的,正在學習的小夥伴歡迎加入。bash

點擊:前端學習圈async

4. 在 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;
}

複製代碼

5. await 多個 async 函數

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

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

複製代碼

6. 建立 Pure objects

你能夠建立一個 100% pure object,它不從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

複製代碼

7. 格式化 JSON 代碼

JSON.stringify除了能夠將一個對象字符化,還能夠格式化輸出 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" // => } // => } // =>}"


複製代碼

8. 從數組中移除重複元素

經過使用集合語法和 Spread 操做,能夠很容易將重複的元素移除:

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

複製代碼

9. 平鋪多維數組

使用 Spread 操做平鋪嵌套多維數組:

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

這裏推薦一下個人前端學習交流羣:731771211,裏面都是學習前端的從最基礎的HTML+CSS+JS【炫酷特效,遊戲,插件封裝,設計模式】到移動端HTML5的項目實戰的學習資料都有整理,送給每一位前端小夥伴。最新技術,與企業需求同步。好友都在裏面學習交流,天天都會有大牛定時講解前端技術!

點擊:加入

相關文章
相關標籤/搜索