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 = this
let res = ''
if(number < 0){
return new Error('Illegal count!')
}
while(number) {
res += str
number--
}
return res
}

利用concat
String.prototype.myRepeat = function(number=1) {
return n>=0 ? this.concat(this.myRepeat(--number)) : ''
}

文章介绍了如何使用JavaScript为Array原型添加自定义方法,如myflat实现数组扁平化,myPush和myFilter用于数组操作,myMap处理数组并保持原数组不变。还展示了如何利用现有方法如concat和repeat实现重复字符串功能。
249

被折叠的 条评论
为什么被折叠?



