一、如何定义
项目中,需要使用到Array的flat方法,结果有兼容问题,于是重写
if (!Array.prototype.flat) {
Array.prototype.flat = function(count) {
console.log('flat-----------');
let c = count || 1;
let len = this.length;
let exe = [];
if (this.length == 0) return this;
while (c--) {
let _arr = [];
let flag = false;
if (exe.length == 0) {
flag = true;
for (let i = 0; i < len; i++) {
if (this[i] instanceof Array) {
exe.push(...this[i]);
} else {
exe.push(this[i]);
}
}
} else {
for (let i = 0; i < exe.length; i++) {
if (exe[i] instanceof Array) {
flag = true;
_arr.push(...exe[i]);
} else {
_arr.push(exe[i]);
}
}
exe = _arr;
}
if (!flag && c == Infinity) {
break;
}
}
return exe;
};
}
二、如何使用
1、使用的地方引入
import "./utils";
2、使用
const arr = [[1, 2, 3], [1, 2, 3]];
console.log('rr---', arr.flat());
三、没想好起什么标题
怎么在原型定义或者重写方法?这个问题很早以前就研究过,现在又忘记了,算了,记录下来吧,哪天忘记了直接拿来看看。
文章中使用的代码参考:https://blog.csdn.net/zero_person_xianzi/article/details/95488825