Array
1.forEach
let arr = [
{ name: 'Eric', age: 18, sex: '男' },
{ name: 'Mary', age: 22, sex: '女' },
{ name: 'Rose', age: 25, sex: '女' },
]
Array.prototype.xf_forEach = function (callback, curThis) {
for (let i = 0; i < this.length; i++) {
console.log('this是谁的',this);
callback.bind(curThis, this[i], i, this)()
}
}
arr.xf_forEach((item, index, curarr) => {
console.log(item, index, curarr);
})
2.map 返回一个新数组
Array.prototype.xf_map = function (callback, curThis) {
let res = [];
for (let i = 0; i < this.length; i++) {
res.push(callback.bind(curThis, this[i], i, this)());
}
return res;
};
arr.xf_map((item, index, curarr) => {
console.log(item, index, curarr);
})
3.filter
Array.prototype.xf_filter = function (callback, curThis) {
let res = []
for (let i = 0; i < this.length; i++) {
callback.call(curThis, this[i], i, this) && res.push(this[i])
}
return res
}
console.log(arr.xf_filter(item => item.age === 18));
4.every
Array.prototype.xf_every = function (callback, curThis) {
let flag = true;
let len = this.length;
for (let i = 0; i < len; i++) {
flag = callback.call(curThis, this[i], i, this);
if (!flag) break;
}
return flag;
};
console.log(arr.xf_every(item => item.age >= 22));
5.some
Array.prototype.xf_some = function (callback, curThis) {
let flag = false;
for (var i = 0; i < this.length; i++) {
flag = callback.apply(curThis, [this[i], i, this]);
if (flag) break;
}
return flag;
};
console.log(arr.xf_some(item => item.age > 25));
6.findIndex
Array.prototype.xf_findIndex = function(callback, curThis) {
for(let i = 0; i < this.length; i++){
if(callback.apply(curThis, [this[i], i ,this])){
return i
}
}
return -1
}
console.log(arr.xf_findIndex(item => item.age === 18));
7.find
Array.prototype.xf_find = function(callback, curThis) {
for(let i = 0; i < this.length; i++){
if(callback.call(curThis, this[i], i ,this)){
return this[i]
}
}
return undefined
}
console.log(arr.xf_find(item => item.age === 18));
8.join
let arr1 = [1, 2, 3]
Array.prototype.xf_join = function(s) {
let str = ''
for(let i = 0; i < this.length; i++){
str = i === 0 ? `${str}${this[i]}`: `${str}${s}${this[i]}`
}
return str
}
console.log(arr1.xf_join('+'));
9.flat
let arr3 = [1, [2, 3, [4, 5]], [8, 9]]
Array.prototype.xf_flat = function() {
let arr = this
while(arr.some(item => Array.isArray(item))){
arr = [].concat(...arr)
}
return arr
}
console.log(arr3.xf_flat());