flat
借助上面递归concat扁平化即可
Array.prototype.myflat = function(deep=1) {let res = []deep--for(const element of this) {if(Array.isArray(element) && deep) {res = res.concat(element.myflat(deep))}else{res.push(element)}}return res
}
push
根据我们对push的认识写就行
Array.prototype.myPush = function(...args) {for(let i=0; i<args.length; i++) {this[this.length] = args[i]}return this.length
}
filter
也很简单,只是注意不改变原数组
Array.prototype.myFilter = function(callback) {const res = []for(let i=0; i<this.length; i++){callback(this[i], i, this) && res.push(this[i])}return res
}
map
同样不改变原数组,根据传入的函数返回值修改对应项就行
Array.prototype.myMap = function(callback) {const res = []for(let i=0; i<this.length; i++){res.push(callback(this[i], i, this))}return res
}
repeat
把一个字符串copy指定次数(向下取整)
遍历
String.prototype.myRepeat = function(number=1) {let str = thislet res = ''if(number < 0){return new Error('Illegal count!')}while(number) {res += strnumber--}return res
}
利用concat
String.prototype.myRepeat = function(number=1) {return n>=0 ? this.concat(this.myRepeat(--number)) : ''
}