国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 語言 > JavaScript > 正文

ES6 中可以提升幸福度的小功能

2024-05-06 15:32:04
字體:
來源:轉載
供稿:網友

一、變量解構賦值的用途

1)交換變量的值

let x = 1;let y = 2;[x, y] = [y, x]

2)從函數返回多個值

// 返回一個數組function example(){  return [1, 2, 4];}let [a, b, c] = example() // 返回一個對象function example(){  return {    foo:1,    bar: 2  }}let {foo, bar} = example(); 或者 ( {foo, bar} = example() )

3)提取JSON數據

let jsonData = { id:42, status: "OK", data: [867, 5309]};let { id, status, data: number} = jsonData;

4)輸入模塊的指定方法

加載模塊時,往往需要指定輸入的方法,解構賦值使得輸入語句非常清晰

const { SourceMapConsumer, SourceNode } = require("source-map")

5) 數組復制的功能

在es5中,開發者經常使用 concat() 方法克隆數組:

// 在 es5 中克隆數組var colors = [ 'red', 'green', 'blue' ];var clonedColors = colors.concat();console.log(clonedColors); // "[red, green, blue]"

concat() 方法的設計初衷是連接兩個數組,如果調用時不傳遞參數就會返回當前數組的副本。在es6中可以通過不定元素的語法來實現相同的目標:

let colors = [ 'red', 'green', 'blue' ]let [ ...clonedColors ] = colors;console.log(clonedColors); // "[red, green, blue]"

6) 結合Set集合,創建一個無重復元素的數組

function eliminateDuplicates(items) {  return [...new Set(items)]}let numbers = [1, 2, 3, 3, 3, 4, 5];let noDuplicates = eliminateDuplicates(numbers );console.log(noDuplicates ); // [1,2,3,4,5]

7) 使用apply 把兩個數據合并成一個

var arra1 = [{ name: '小智', age: 26}]var arra2 = [{ name: '大智', age: 27}]arra1.push.apply(arra1, arra2)console.log(arra1)

二、函數的用處(常見就不多說了)

1)創建立即執行函數表達式

// es5let person = function(name) { return {  getName: function() {   return name;  } }}('小智');console.log(person.getName()); // 小智

在這段代碼中,立即執行函數表達式創建了一個包含getName() 方法的新對象,將參數 name 作為該對象的一個私有成員返回給函數的調用者。

只要箭頭函數包裹在小括號里,就可以用它實現相同的功能

// es6let person = ((name) => { return {  getName: function() {   return name;  } }})('小智2');console.log(person.getName()); //小智

2.利用參數默認值可以指定某一個參數不得省略,如果省略就拋出一個錯誤。

function throwEmptyError() {  throw new Error('參數不能為空');}function foo(mustBeParams = throwEmptyError() ){  return mustBeParams();}foo() // 參數不能為空

三、擴展對象的功能性讓代碼更加簡潔

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表

圖片精選

主站蜘蛛池模板: 高邑县| 衡南县| 双牌县| 道真| 沂源县| 徐州市| 开阳县| 奉化市| 河源市| 玛曲县| 梅河口市| 锡林郭勒盟| 琼结县| 尚义县| 临泉县| 上栗县| 青州市| 丽水市| 清水河县| 介休市| 贡嘎县| 乌兰浩特市| 崇明县| 商河县| 斗六市| 大余县| 凤山市| 和顺县| 敦化市| 珠海市| 蒲城县| 酉阳| 尚义县| 塘沽区| 静乐县| 西青区| 浏阳市| 廊坊市| 红原县| 抚顺县| 琼海市|