ZhangYang's Blog

ES5数组扩展方法源代码

join

应用

1
2
var array = ['a','b','c']
array.join('-') // 结果是'a-b-c'

源代码实现

1.array.join是Array.prototype.join对应的函数

2.array.join(‘-‘)等价于array.join.call(array,’-‘)

3.join函数的this和arguments[0]可以得到array和’-‘两个值

1
2
3
4
5
6
7
8
Array.prototype.join = function(char){
let result = this[0] || ''
let length = this.length
for(let i=1; i< length; i++){
result += char + this[i]
}
return result
}

slice

应用

1
2
3
4
5
6
7
8
9
var a = ['a', 'b', 'c'];
a.slice(1) // ["b", "c"]
a.slice(1, 2) // ["b"]
a.slice() // ["a", "b", "c"]
// 将伪数组转化成数组
array = Array.prototye.slice.call(arrayLike)
或者
array = [].slice.call(arrayLike)

源代码实现

1
2
3
4
5
6
7
8
9
Array.prototype.slice = function(begin, end){
let result = []
begin = begin || 0
end = end || this.length
for(let i = begin; i< end; i++){
result.push(this[i])
}
return result
}

sort

应用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
['d', 'c', 'b', 'a'].sort()
// ['a', 'b', 'c', 'd']
[4, 3, 2, 1].sort()
// [1, 2, 3, 4]
[11, 101].sort()
// [101, 11]
[10111, 1101, 111].sort()
// [10111, 1101, 111]
[10111, 1101, 111].sort(function (a, b) {
return a - b;
})
// [111, 1101, 10111]

源代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
// 选择排序
Array.prototype.sort = function(fn){
fn = fn || (a,b)=> a-b
let roundCount = this.length - 1 // 比较的轮数
for(let i = 0; i < roundCount; i++){
let minIndex = this[i]
for(let k = i+1; k < this.length; k++){
if( fn.call(null, this[k],this[i]) < 0 ){
[ this[i], this[k] ] = [ this[k], this[i] ]
}
}
}
}

forEach

实现

1
2
3
4
5
6
[2, 5, 9].forEach(function (element, index, array) {
console.log('[' + index + '] = ' + element)
});
// [0] = 2
// [1] = 5
// [2] = 9

源代码实现

1
2
3
4
5
6
7
Array.prototype.forEach = function(fn){
for(let i=0;i<this.length; i++){
if(i in this){
fn.call(undefined, this[i], i, this)
}
}
}

map

应用

1
2
3
4
5
6
7
var numbers = [1, 2, 3]
numbers.map(function (n) {
return n + 1
});
// [2, 3, 4]
numbers
// [1, 2, 3]

源代码实现

1
2
3
4
5
6
7
8
9
Array.prototype.map = 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
}

filter

应用

1
2
3
4
[1, 2, 3, 4, 5].filter(function (elem) {
return (elem > 3);
})
// [4, 5]

源代码实现

1
2
3
4
5
6
7
8
9
10
11
12
Arra.prototype.filter = function(fn){
let result = []
let 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

应用

1
2
3
4
5
6
7
8
9
[1, 2, 3, 4, 5].reduce(function (a, b) {
console.log(a, b);
return a + b;
})
// 1 2
// 3 3
// 6 4
// 10 5
//最后结果:15

源代码实现

1
2
3
4
5
6
7
8
9
Arra.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
}