ES6/7之拋棄Underscore

如無特殊注釋,本文中所有的
v 表示value,
i 表示index,
arr 表示array

1.數(shù)組遍歷

---underscore
_.firEach(arr,i)
ES6寫法:
var arr = [7, -1, 9, 7, -7, -10, 1, -2, 6, 3];
/**
 * forEach(循環(huán))和map(映射(進(jìn)去幾個,出來幾個)):
 * 1.可以遍歷數(shù)組
 * 2.不改變原來的數(shù)組
 * 區(qū)別:
 * 數(shù)組的forEach方法不可以返回一個新的數(shù)組,
 * 但map方法可以返回一個新的數(shù)組,其元素是原數(shù)組的每個元素運算之后的結(jié)果
 */
//b的結(jié)果是undefined
let b = arr.forEach((v,i,array)=>{
    return v*=2;
})

//c的結(jié)果是arr的每一個元素都元素之后返回的結(jié)果
let c = arr.map((v,i,array)=>{
   return v*=2;
})
console.log(b,c)
//undefined  [14, -2, 18, 14, -14, -20, 2, -4, 12, 6]

2.accumulate a single value from an array(匯總)

underscore
_.reduce()
ES6
arr.reduce((a,b)=>{
    console.log(a+b)//開始:把第一項和第二項進(jìn)行運算;然后:本上一次的結(jié)果和下一項進(jìn)行運算
    return a+=b
})

3.判斷一些項或者所有項是否滿足某條件:

some和every(數(shù)組中的一項或者幾項滿足某個條件,即:結(jié)果返回一個Boolean值)
var arr = [7, -1, 9, 7, -7, -10, 1, -2, 6, 3];
let a1 = arr.some(i=>{
    return i===-10;
})
let a2 = arr.every(i=>{
    return i===-10;
})
console.log(a1,a2)//true false

4.數(shù)組去重

underscore
_.uniq(arr)
ES6
var arr = [7, -1, 9, 7, -7, -10, 1, -2, 6, 3];
let arr1 = [...new Set(arr)];
console.log(arr1)//得到的便是去重后的數(shù)組
//所以說:
//數(shù)組轉(zhuǎn)set結(jié)構(gòu):new Set(arr)
//Set結(jié)構(gòu)轉(zhuǎn)數(shù)組:[...seTarr]

5.在數(shù)組中查找某元素

//arr.find()很智障,返回第一個你想要查找的值,不知道有什么卵用,沒有返回undefined,用于判斷數(shù)組中是否存在這個玩意兒
let b1 = arr.find((i)=>{
    return i===3
})
console.log(b1)

//arr.findIndex()返回的是第一個值為7的元素的下標(biāo)
let b2 = arr.findIndex((i)=>{
    return i===7
})
console.log(b2)

6.判斷數(shù)組是否包含某個元素

ES6
console.log(arr.includes(3))

7.參數(shù)轉(zhuǎn)化為數(shù)組

function silyB(a,s,d,f,g){
    console.log([...arguments])
}
silyB(1,2,3,4,5)// [1, 2, 3, 4, 5]
silyB(1,2)//[1,2]

8.過濾器

arr.filter((i)=>{
    return i>=5
})

9.把對象的屬性名或者屬性值拆分出來,形成一個數(shù)組

ES6
var obj = {
    name:"gouZi",
    age:12,
    hobbies:["a","b","c"],
    eat:(a)=>{return Math.pow(100,a)}
}

let cdd = Object.keys(obj);
console.log(cdd)
//["name", "age", "hobbies", "eat"]
let aaaa = Object.keys(obj).map(key => obj[key])
console.log(aaaa)

10.對象的屬性的個數(shù)

ES6

Object.keys(obj).length

11.獲取時間戳

Date().now()
?著作權(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ù)。

相關(guān)閱讀更多精彩內(nèi)容

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