概要
- 實(shí)現(xiàn)一些常用的數(shù)組操作函數(shù)。
join
用法:[1, 2, 3].join('-') // "1-2-3"
實(shí)現(xiàn):
Array.prototype.join = function(char){
let result = this[0] || ''
for(let i=1; i<this.length; i++){
result += char + this[i]
}
return result
}
slice
用法:[1, 2, 3, 4].slice(1, 3) // [2, 3]
實(shí)現(xiàn):
Array.prototype.slice = function(startIndex, endIndex){
console.log(1)
let result = [],
start = startIndex || 0,
end = endIndex || this.length
for(let i=start; i<end; i++){
result.push(this[i])
}
return result
}
sort
用法:[1,2,3].sort( (a,b)=>{a-b} )
實(shí)現(xiàn):一般源代碼使用的是堆排序或是快速排序,這里使用復(fù)雜度較大的選擇排序
Array.prototype.sort = function(fn){
let sortFn = fn || function(a,b){return a-b}
for(let i=0; i<this.length-1; i++){
for(let j=i+1; j<this.length; j++){
if( sortFn.call(undefined, this[i], this[j]) < 0 ){
[this[i], this[j]] = [this[j], this[i]]
}
}
}
}
forEach
用法: 根據(jù)函數(shù)對(duì)每一項(xiàng)做相應(yīng)操作。
實(shí)現(xiàn):
Array.prototype.forEach = function(fn){
for(let i=0; i<this.length; i++){
if(i in this){
fn.call(undefined, this[i], i, this)
}
}
}
forEach 與 for 的區(qū)別:
- forEach 不能 break。
- forEach 用到了函數(shù),所以每次迭代都會(huì)有一個(gè)新的函數(shù)作用域;而 for 循環(huán)只有一個(gè)作用域。
map
用法: 根據(jù)函數(shù)對(duì)每一項(xiàng)做相應(yīng)操作,并返回一個(gè)新的數(shù)組。
實(shí)現(xiàn):
Array.prototype.forEach = function(fn){
let result = []
for(let i=0; i<this.length; i++){
if(i in this){
result[i] = fn.call(undefined, this[i], i, this)
}
}
return result
}
map 與 forEach 的區(qū)別:
- map 有返回值,所有 forEach 都可以用 map 來代替。
filter
用法:返回符合傳入函數(shù)返回值的項(xiàng)
實(shí)現(xiàn):
Array.prototype.forEach = function(fn){
let result = [],
temp
for(let i=0; i<this.length; i++){
if(i in this){
if(temp = fn.call(undefined, this[i], i, this)){
result.push(this[i])
}
}
}
return result
}
reduce
用法:將每一項(xiàng)通過函數(shù)作用與后一項(xiàng),返回一個(gè)結(jié)果
實(shí)現(xiàn):
Array.prototype.reduce = function(fn,init){
let result = init
for(let i=0; i<this.length; i++){
if(i in this){
result = fn.call(undefined, result, this[i], i, this)
}
}
return result
}
map filter reduce 之間的聯(lián)系
- 用 reduce 表示 map
array2 = array.map( value => value + 1 )
可以寫作
array2 = array.reduce((result, value)=>{
result.push(value + 1)
return result
}, [])
- 用 reduce 表示 filter
array2 = array.filter( value => value % 2 === 0 )
可以寫作
array2 = array.reduce((result, value)=>{
if( value % 2 === 0 ){
result.push(value)
}
return result
}, [])