var arr = [1, 2, null, undefined, 3, 0, 4]; arr = $.grep(arr, n => n == 0 || n); console.log(arr); // [1, 2, 3, 0, 4]
4. 使用underscore.js或lodash
1 2 3 4 5 6 7 8 9
// underscore.js var arr = [1, false, "", undefined, 2]; var filtered = _.filter(arr, Boolean); console.log(filtered); // [1, 2]
// lodash var arr = [1, false, "", undefined, 2]; var filtered = _.compact(arr); console.log(filtered); // [1, 2]
5. 自定义函数
1 2 3 4 5 6 7 8 9 10 11 12 13
functionremoveFalsyElementsFromArray(someArray) { var newArray = []; for (var index = 0; index < someArray.length; index++) { if (someArray[index]) { newArray.push(someArray[index]); } } return newArray; }
var arr = [1, 2, null, undefined, 3, 0, 4]; var filtered = removeFalsyElementsFromArray(arr); console.log(filtered); // [1, 2, 3, 4]
if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { 'use strict'; if (this === void0 || this === null) { thrownewTypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fun !== 'function') { thrownewTypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; }