熟練掌握JS中Array常用方法、迭代器是必要的,本文從常用方法及使用場景進行舉例和分析墨礁。
導讀
帶新人的時候醋奠,有時候發(fā)現(xiàn)他們對Array原生方法并不熟悉榛臼,不知道原生提供的哪些,以至于編程時無法靈活使用窜司。有的在用到Array時會google后查一下沛善,恰巧沒有搜索到自己想要的知識點后,就噼里啪啦敲起代碼塞祈,用自己用最熟悉的for循環(huán)(迭代器他們一般也是只用for金刁、map)去實現(xiàn)reverse、splice這些方法议薪。
環(huán)境
MacOS v10.14.3
Node.js v10.15.2
Chrome
場景一:對原數(shù)組進行操作
splice:對原數(shù)組中間部分進行增加和刪除
代碼示例:
// splice(startIndex, count)
// 與slice類似尤蛮,但會返回一個截取的子集所創(chuàng)建的新數(shù)組
var arr1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var newArr1 = arr1.splice(2, 2)
console.log("arr1:", arr1)
// arr1: [ 1, 2, 5, 6, 7, 8, 9 ]
console.log("newArr1:", newArr1)
// newArr1: [ 3, 4 ]
// splice(startIndex, deleteCount,item...)
var arr2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]
var newArr2 = arr2.splice(2, 2, 'a', 'b', 'c')
console.log("arr2:", arr2)
// arr2: [ 1, 2, 'a', 'b', 'c', 5, 6, 7, 8, 9 ]
console.log("newArr2:", newArr2)
// newArr2: [ 3, 4 ]
對原數(shù)組首末進行增加和刪除(shift、unshift斯议、push产捞、pop)
代碼示例:
// shift和pop
var arr1 = [1,2,3,4,5,6]
var newArr1 = arr1.shift()
console.log('arr1:', arr1) // arr1: [ 2, 3, 4, 5, 6 ]
console.log('newArr1:', newArr1) // newArr1: 1
var arr2 = [1,2,3,4,5,6]
var newArr2 = arr2.pop()
console.log('arr2:', arr2) //arr2: [ 1, 2, 3, 4, 5 ]
console.log('newArr2:', newArr2) // newArr2: 6
// unshift和push
var arr3 = [1,2,3,4,5,6]
var newArr3 = arr3.push(100)
console.log('arr3:', arr3) // arr3: [ 1, 2, 3, 4, 5, 6, 100 ]
console.log('newArr3:', newArr3) // newArr3: 7
var arr4 = [1,2,3,4,5,6]
var newArr4 = arr4.unshift(100)
console.log('arr4:', arr4) // arr4: [ 100, 1, 2, 3, 4, 5, 6 ]
console.log('newArr4:', newArr4) // newArr4: 7
場景二:遍歷數(shù)組(map,filter, every捅位,some轧葛,reduce,reduceRight)
map艇搀,filter:生成新數(shù)組
代碼示例:
// filter傳入一個返回值為布爾類型的函數(shù),返回一個函數(shù)返回值都為true的新數(shù)組
var arr1 = [1, 2, 3, 4, 5]
function isEvenNumver(x) {
return x % 2 == 0 ? true : false
}
var newArr1 = arr1.filter(isEvenNumver)
console.log('arr1.filter(isEvenNumver)', newArr1)
// map,返回一個函數(shù)處理過了的新數(shù)組
var arr2 = [1, 2, 3, 4, 5]
function double(x) {
return x * 2
}
var newArr2 = arr2.map(double)
console.log('newArr2:', newArr2) // newArr2: [ 2, 4, 6, 8, 10 ]
forEach尿扯、reduce、reduceRight焰雕、every衷笋、some:不生成新數(shù)組
代碼示例:
// foreach
var arr = [1, 2, 3, 4, 5]
function addOne(x) {
console.log(x + 1)
}
arr.forEach(addOne)
// reduce
// array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
var arr = [1, 2, 3, 4, 5]
function cheng(total, currentValue) {
console.log(total, currentValue)//1 2,2 3,6 4,24 5
return total * currentValue
}
console.log('arr.reduce(cheng):', arr.reduce(cheng))//arr.reduce(cheng): 120
// reduceRight與reduce作用一致,從最后一個元素開始運行
var arr = [1, 2, 3, 4, 5]
function cheng(value, item) {
console.log(value, item)//5 4,20 3, 60 2,120 1
return value * item
}
console.log('arr.reduce(cheng):', arr.reduceRight(cheng))//arr.reduce(cheng): 120
// every
var arr4 = [1,2,3,4,5,6,7]
function lessThree(x){
return x<3
}
console.log('arr4.every(lessThree):',arr4.every(lessThree))// false
// some
var arr4 = [1,2,3,4,5,6,7]
function lessThree(x){
return x<3
}
console.log('arr4.some(lessThree):',arr4.some(lessThree))// true
場景三:字符串與數(shù)組相互轉(zhuǎn)換(join矩屁、split辟宗、toString)
代碼示例:
//構(gòu)造一個大數(shù)組
var arr = []
for (var i = 0; i < 500; i++) {
arr.push(i)
}
// join
//array.join(separator),default separator char ,
var begin, end, newArray, result
begin = new Date()
result = arr.join('-')
// console.log('arr.join:', result)
end = new Date()
console.log('消耗時間(ms):', end - begin)
// 運算符+
newArray = ''
begin = new Date()
for (var i = 0; i < arr.length; i++) {
newArray = newArray + '-' + arr[i]
}
// console.log('operator +: ', newArray)
end = new Date()
console.log('消耗時間(ms):', end - begin)
//split
var str = 'a-b-c-d'
console.log('str.split("-"):',str.split('-')) //[ 'a', 'b', 'c', 'd' ]
場景四:不改變原數(shù)組爵赵,生成新數(shù)組(concat、slice)
concat:
生成一個新數(shù)組泊脐,新數(shù)組包含原來數(shù)組的淺拷貝空幻,然后加上參數(shù)。
slice:
生成一個新數(shù)組容客,新數(shù)組是從原來數(shù)組中切片秕铛,不改變原數(shù)組。
代碼示例:
var arr1 = [{ id: 1, value: 100 }, 2, 3, 4, 5]
var arr2 = ['a', 'b', 'c']
console.log('arr1:', arr1)
console.log('arr2:', arr2)
// arr1: [ { id: 1, value: 100 }, 2, 3, 4, 5 ]
// arr2: [ 'a', 'b', 'c' ]
console.log('arr1.concat(arr2):', arr1.concat(arr2))
// arr1.concat(arr2): [ { id: 1, value: 100 }, 2, 3, 4, 5, 'a', 'b', 'c' ]
console.log('arr2.concat(arr1):', arr2.concat(arr1))
// arr2.concat(arr1): [ 'a', 'b', 'c', { id: 1, value: 100 }, 2, 3, 4, 5 ]
var newArr = arr1.concat(arr2)
// 注意是淺拷貝
newArr[0].value = '500'
console.log('newArr:', newArr)
console.log('arr1:', arr1)
// newArr: [ { id: 1, value: '500' }, 2, 3, 4, 5, 'a', 'b', 'c' ]
// arr1: [ { id: 1, value: '500' }, 2, 3, 4, 5 ]
// slice(start,end)
var arr3 = [1,2,3,4,5]
console.log('arr3.slice(2,3):',arr3.slice(2,3))
場景五:數(shù)組排序及倒序(sort缩挑、reverse)
代碼示例:
var nums = [1, 2, 3, 4, 5];
nums.reverse();
console.log(nums); // 5,4,3,2,1
var arr1 = [1, 2, 100, 200]
arr1.sort() // 默認字符串但两,整型都會按字符排序
console.log('arr1', arr1)// [ 1, 100, 2, 200 ]
var arr2 = [1, 2, 100, 200]
arr2.sort((a, b) => a - b)
console.log('arr2', arr2)// [ 1, 2, 100, 200 ]
總結(jié)
很多小伙伴遇到splice、slice就分不清楚供置,從沒用過shift谨湘、unshift,遍歷數(shù)組總是for芥丧、map等等紧阔。本文根據(jù)數(shù)組的使用場景進行了總結(jié),希望能有所幫助娄柳。