JavaScript 数组Array-filter()方法
时间:2019-08-20 13:50:49 来源:igfitidea点击:
说明
Javascript array filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。
语法
array.filter(callback[, thisObject]);
参数明细
callback−函数,用于测试数组的每个元素。
传递给callback的参数有:
- value - 当前索引的值。
- index - 当前索引
- array - 数组
thisObject—执行回调时用作此对象的对象。
返回值
返回新创建的数组,其中包含来自传递的迭代的所有值。
兼容性
此方法是ECMA-262标准的JavaScript扩展;因此,它可能不会出现在该标准的其他实现中。要使其正常工作,我们需要在脚本的顶部添加以下代码。
if (!Array.prototype.filter) {
Array.prototype.filter = function(fun /*, thisp*/) {
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++) {
if (i in this) {
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
示例 - 普通用法
var array = [2, 4, 8];
var result = array.filter(function () {
console.log(this);
return true;
});
console.log(result); // [2, 4, 8]
示例 - 使用callbak参数
var arr = [2, 4, 8];
var result = arr.filter(function (value, index, array) {
console.log(value, index, array);
return true;
});
console.log(result); // [2, 4, 8]
传递自定义的this对象
var array = [2, 4, 8];
var result = array.filter(function () {
console.log(this);
return true;
}, document.location); // 传递document.location作为this值
console.log(result); // [2, 4, 8]
示例 - 模拟false的情况
var array = [2, 4, 8];
var result = array.filter(function (value) {
if (value === 4) {
return false;
}
return true;
});
console.log(result); // [2, 8]
console.log(array); // [2, 4, 8]

