JS中 filter 方法用於對數組進行過濾
實例 :返回數組nums中所有大於5的元素
var nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; var res = nums.filter((num) => { return num > 5; }); console.log(res); // [6, 7, 8, 9, 10]
IE不兼容解決辦法:寫個共用方法,
Array.prototype.myfilter = 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; };
// 頁面引用之后調用
//數組對象ArrData遍歷之后 返回過濾后的新數組對象 tina var tina = ArrData.myfilter(function(item, inde, array){ return item.mapid == 5; //過濾條件,根據自己需求修改 })