es6函式新功能使用(V客學院知識分享)

2022-08-31 20:57:10 字數 2507 閱讀 4809

reduce 可以用來彙總

資料

const customer = [

, ,

];const totalcount = customer.reduce((total, item) =>

total + item.count,

0 // total 的初始值

);// now totalcount = 92

把乙個物件陣列變成乙個以陣列中各個物件的 id 為屬性名,物件本身為屬性值的物件。haoduoshipin

map 可以理解為是陣列的轉換器,依次對陣列中的每個元素做變換進而得到乙個新的陣列。

const integers = [1, 2, 3, 4, 6, 7];

const twoxintegers = integers.map(i => i*2);

// twoxintegers are now [2, 4, 6, 8, 12, 14]

// integers陣列並不會受到影響

const posts = [

, ,

];// find the title of post whose id is 1

const title = posts.find(p => p.id === 1).title;

唉~ 使用了半年的 es6才發現有這麼好用的東西,譯者傻缺還像下面這麼寫過呢

篩選出陣列中

某些符合條件的元素組成新的陣列

const integers = [1, 2, 3, 4, 6, 7];

const evenintegers = integers.filter(i => i % 2 === 0);

// evenintegers are [2, 4, 6]

陣列concat請大家自行思考下filter和find的區別

const arr1 = [1, 2, 3, 4, 5];

const arr2 = [6, 7, 8, 9, 0];

const arrtarget = [...arr1, ...arr2];

// [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]

function operation(query, option = {}) ;

// ....

return param;

}let opt = ;

let q = ;

operation(q, opt);

//

物件是引用傳參的,所以函式內部應該盡可能的保證傳入的引數不受到汙染。

const dynamickey = 'wearsspectacles';

const user = ;

const updateduser = ;

// updateduser is

將物件轉換為query字串

const params = ;

const query = '?' + object.keys(params)

.map(k =>

encodeuricomponent(k) + '=' + encodeuricomponent(params[k])

) .join('&')

;// encodeuricomponent encodes special characters like spaces, hashes

// query is now "color=red&minprice=8000&maxprice=10000"

const posts = [

, ,

, ];// to find index of element with id 131

const requiredindex = posts.map(p => p.id).indexof(131);

const posts = [

, ,

, ];const index = posts.findindex(p => p.id === 131)

const user = ;

const userwithoutpassword = object.keys(user)

.filter(key => key !== 'password')

.map(key => )

.reducer((accumulator, current) =>

(),{}

);// userwithoutpassword becomes

這裡我認為原作者有點為了函式式程式設計而函式式了,下面是我的解決方案:

const user = ;

const newuser = ;

delete newuser.password;

//

筆記 ES6 新功能

es6 新功能 const 宣告常量,let 宣告變數。都不可重複宣告 塊級函式 箭頭函式 表示式體 語句體 lexical this 函式引數 預設值 剩餘引數 spread 操作符 字串插值 字面量 二進位制 0b1011 八進位制 073434 物件屬性 屬性簡寫 計算屬性名 方法屬性簡寫 解...

ES6 功能 箭頭函式

箭頭函式 function qh n1 console.log 普通函式 console.log qh 10 const sum n2 console.log es6沒省略寫法 console.log sum 9 const sum1 n3 console.log es6省略引數括號寫法 conso...

React 1 js基礎和ES6新功能

這裡只寫一些補充的和遺漏的知識點 var beyond 為物件定義方法 beyond.showartist function 和 function kitchen strings,values 下圖為輸出的結果 以上strings輸出的為字元,values輸出的為變數。function breakf...