5 分鐘掌握 JavaScript 實用竅門

簡評:一開始 JavaScript 只是為網(wǎng)頁增添一些實時動畫效果,現(xiàn)在 JS 已經(jīng)能做到前后端通吃了,而且還是年度流行語言。本文分享幾則 JS 小竅門,可以讓你事半功倍 ~

1.刪除數(shù)組尾部元素

一個簡單方法就是改變數(shù)組的 length 值:

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.使用對象解構(gòu)來處理數(shù)組

可以使用對象解構(gòu)的語法來獲取數(shù)組的元素:
數(shù)組解構(gòu)

// 以前,為變量賦值,只能直接指定值。

let a = 1;
let b = 2;
let c = 3;
// ES6 允許寫成下面這樣。

let [a, b, c] = [1, 2, 3];

let [foo, [[bar], baz]] = [1, [[2], 3]];
foo // 1
bar // 2
baz // 3

對象解構(gòu)

let { bar, foo } = { foo: "aaa", bar: "bbb" };
foo // "aaa"
bar // "bbb"

let { baz } = { foo: "aaa", bar: "bbb" };
baz // undefined

字符串解構(gòu)

const [a, b, c, d, e] = 'hello';
a // "h"
b // "e"
c // "l"
d // "l"
e // "o"
類似數(shù)組的對象都有一個length屬性,因此還可以對這個屬性解構(gòu)賦值。

let {length : len} = 'hello';
len // 5
const csvFileLine = '1997,John Doe,US,john@doe.com,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.創(chuàng)建 pure objects

你可以創(chuàng)建一個 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
5.格式化 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"
// =>        }
// =>    }
// =>}"
6.從數(shù)組中移除重復(fù)元素

通過使用集合語法和 Spread 操作,可以很容易將重復(fù)的元素移除:

const removeDuplicateItems = arr => [...new Set(arr)];
removeDuplicateItems([42, 'foo', 42, 'foo', true, true]);
//=> [42, "foo", true]
7.平鋪多維數(shù)組

使用 Spread 操作平鋪嵌套多維數(shù)組:

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

不過上面的方法僅適用于二維數(shù)組,但是通過遞歸,就可以平鋪任意維度的嵌套數(shù)組了:

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 ~

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容