1、从数组中删除某一个指定的元素
Array.prototype.remove = function (val) {
let index = this.indexOf(val);
if (index > -1) {
this.splice(index, 1);
}
};
2、去除数组中的空值
Array.prototype.bouncer = function () {
return this.filter(item => {/* fliter 返回结果是true的*/
return item;
});
}
let arr = [1, null, 2, 3, undefined, '', 4]
console.log(arr)
console.log(arr.bouncer())
3、 数组是否包含另一个数组
function isContained(a, b) {
/* * a是大数组b是小数组 * 数组是否包含另一个数组 */
if (!(a instanceof Array) || !(b instanceof Array)) return false;
if (a.length < b.length) return false;
let aStr = a.toString();
for (let i = 0, len = b.length; i < len; i++) {
if (aStr.indexOf(b[i]) == -1) return false;
}
return true;
}
let arr1 = [1, 2, 3, 4, 6]
let arr2 = [1, 2, 6, 3]
console.log(isContained(arr1, arr2))
原型上版:
Array.prototype.isContained = function (b) {
if (!b instanceof Array) return false
if (this.length < b.length) return false
let aStr = this.toString();
for (let i = 0, len = b.length; i < len; i++) {
if (aStr.indexOf(b[i]) == -1) return false;
}
return true;
}
let arr1 = [1, 2, 3, 4, 6]
let arr2 = [1, 2, 6, 3]
console.log(arr1.isContained(arr2))
4、数组去重
Array.prototype.uniq = function (array) {
var temp = []; //一个新的临时数组
for (var i = 0; i < array.length; i++) {
if (temp.indexOf(array[i]) == -1) {
temp.push(array[i]);
}
}
return temp;
}
let arr = [1, 2, 2, 3, 4, 4, 5]
console.log(arr)
console.log(arr.uniq(arr))