function removeFalsyElementsFromArray(someArray) {var newArray = [];for(var index = 0; index < someArray.length; index++) {if(someArray[index]) {newArray.push(someArray[index]);}}return newArray;}
实际上,这里有一个更通用的解决方案:
function removeElementsFromArray(someArray, filter) {var newArray = [];for(var index = 0; index < someArray.length; index++) {if(filter(someArray[index]) == false) {newArray.push(someArray[index]);}}return newArray;}
// then provide one or more filter functions that will// filter out the elements based on some condition:function isNullOrUndefined(item) {return (item == null || typeof(item) == "undefined");}
// then call the function like this:var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];var results = removeElementsFromArray(myArray, isNullOrUndefined);
// results == [1,2,3,3,4,4,5,6]
var array = ["","one",0,"",null,0,1,2,4,"two"];
function isempty(x){if(x!=="")return true;}var res = array.filter(isempty);document.writeln(res.toJSONString());// gives: ["one",0,null,0,1,2,4,"two"]
这是你需要为IE添加的代码,但过滤器和函数式编程是值得的。
//This prototype is provided by the Mozilla foundation and//is distributed under the MIT license.//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
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 thisif (fun.call(thisp, val, i, this))res.push(val);}}
return res;};}
var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],len = arr.length, i;
for(i = 0; i < len; i++ )arr[i] && arr.push(arr[i]); // copy non-empty values to the end of the array
arr.splice(0 , len); // cut the array and leave only the non-empty values// [1,2,3,3,[],Object{},5,6]
jQuery:
var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
arr = $.grep(arr, n => n == 0 || n);// [1, 2, 3, 3, 0, 4, 4, 5, 6]
if (!Array.prototype.filter) {Array.prototype.filter = function(fun/*, thisArg*/) {'use strict';if (this === void 0 || this === null) {throw new TypeError();}var t = Object(this);var len = t.length >>> 0;if (typeof fun !== 'function') {throw new TypeError();}var res = [];var thisArg = arguments.length >= 2 ? arguments[1] : void 0;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;};}
// --- Example ----------var field = [];
field[0] = 'One';field[1] = 1;field[3] = true;field[5] = 43.68;field[7] = 'theLastElement';// --- Example ----------
var originalLength;
// Store the length of the array.originalLength = field.length;
for (var i in field) {// Attach the truthy values upon the end of the array.field.push(field[i]);}
// Delete the original range within the array so that// only the new elements are preserved.field.splice(0, originalLength);
// Removes all falsy valuesarr = arr.filter(function(array_val) { // creates an anonymous filter funcvar x = Boolean(array_val); // checks if val is nullreturn x == true; // returns val to array if not null});
arr = [, ,];console.log(arr[0], 0 in arr, arr.length); // undefined, false, 2; arr[0] is a holearr[42] = 42;console.log(arr[10], 10 in arr, arr.length); // undefined, false, 43; arr[10] is a hole
arr1 = [1, 2, 3];arr1[0] = (void 0);console.log(arr1[0], 0 in arr1); // undefined, true; a[0] is undefined, not a hole
arr2 = [1, 2, 3];delete arr2[0]; // NEVER do this pleaseconsole.log(arr2[0], 0 in arr2, arr2.length); // undefined, false; a[0] is a hole
function removeNil(obj) {// recursively remove null and undefined from nested object too.return JSON.parse(JSON.stringify(obj), (k,v) => {if(v === null || v === '') return undefined;// convert date string to date.if (typeof v === "string" && /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(v))return new Date(v);// remove empty array and object.if(typeof v === 'object' && !Object.keys(v).length) return undefined;return v;});}
function removeNil(obj) {// recursively remove null and undefined from nested object too.return JSON.parse(JSON.stringify(obj), (k,v) => {if(v === null || v === '') return undefined;// convert date string to date.if (typeof v === "string" && /^\d\d\d\d-\d\d-\d\dT\d\d:\d\d:\d\d.\d\d\dZ$/.test(v))return new Date(v);// remove empty array and object.if(typeof v === 'object' && !Object.keys(v).length) return undefined;return v;});}
const ob = {s: 'a',b: 43,countries: [ 'a', 'b', 'c' ],l: null,n: { ks: 'a', efe: null, ce: '' },d: new Date(),nan: NaN,k: undefined,emptyO: {},emptyArr: [],}
const output = removeNil(ob);
console.log(output);console.log('Tests: ', ob.countries.length, typeof(ob.d))