const arr2obj = (array, initVal = true) => array.reduce((total, cur) => {
total[cur] = initVal;
return total;
}, {});
// eslint-disable-next-line no-extend-native
Array.prototype.safeConcat = function (value, forbiddenArr = []) {
const UNDEFINED = undefined;
const NULL = null;
const forbidden = arr2obj([UNDEFINED, NULL, ...forbiddenArr]);
return forbidden[value] ? this : this.concat(value);
};
const arr = [1, 2];
console.log('使用默认的阻止concat的元素:undefined,null');
[
[1, 2, 3],
undefined,
null,
0,
false
].forEach((item) => {
console.log(arr.safeConcat(item));
});
// 使用默认的阻止concat的元素:undefined,null
// [ 1, 2, 1, 2, 3 ]
// [ 1, 2 ]
// [ 1, 2 ]
// [ 1, 2, 0 ]
// [ 1, 2, false ]
console.log('添加自定义阻止concat的元素');
[
[1, 2, 3],
undefined,
null,
0,
false
].forEach((item) => {
console.log(arr.safeConcat(item, [false]));
});
// 添加自定义阻止concat的元素
// [1, 2, 1, 2, 3]
// [1, 2]
// [1, 2]
// [1, 2, 0]
// [1, 2];