初學者學習JavaScript不得不掌握的小竅門

是一種高級編程語言,通過解釋執行。它是一門動態類型,面向對象(基於原型)的直譯語言。它已經由歐洲電腦製造商協會通過ECMAScript實現語言標準化,它被世界上的絕大多數網站所使用。也被世界主流瀏覽器(Chrome、IE、FireFox等)支持。

  • JavaScript組成部分
  1. 文檔對象類型: (DOM) document object module
  2. 瀏覽器對象類型:(BOM) broswer object module
  • JavaScript能幹嘛?
  1. 在HTML靜態頁面中寫動態效果
  2. 對瀏覽器事件作出響應
  3. 在數據提交到後臺之前進行數據驗證
  4. 通過node.js擦作數據庫
  • JavaScript的特點
  1. 腳本語言
  2. 基於對象
  3. 動態性
  4. 跨平臺
初學者學習JavaScript不得不掌握的小竅門

好了,以上小夥伴們就已經瞭解了JavaScript是做什麼的了,也瞭解了它的特點,那麼下面小編就介紹一些JavaScript的實用小技巧。

1.刪除數組尾部元素

一個簡單方法就是改變數組的 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.使用對象解構(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 中的命名參數。

在 ES6 中,你可以直接使用對象解構:

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

// ...

}

讓參數可選也很簡單:

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

// ...

}

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

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

const csvFileLine = '1997,John Doe,US,[email protected],New York';

const { 2: country, 4: state } = csvFileLine.split(',');

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) : flatt

ened;

}

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 ~

分享 IT 技術和行業經驗,請關注- 。


分享到:


相關文章: