2016-09-15 68 views

回答

4

使用lodash,下面從數組中刪除唯一不確定的值:

var array = [ 1, 2, 3, undefined, 0, null ]; 

_.filter(array, function(a){ return !_.isUndefined(a) } 
--> [ 1, 2, 3, 0, null ] 

或者,下面將刪除未定義,0和空值:

_.filter(array) 
--> [1, 2, 3] 

如果你想刪除陣列中的空值和未定義值,但將值保留爲0:

_.filter(array, function(a){ return _.isNumber(a) || _.isString(a) } 
[ 1, 2, 3, 0 ] 
4

不需要適用於擁有現代瀏覽器的圖書館filter是內置的。

var arr = [ 1, 2, 3, undefined, 0, null ]; 
 
    var updated = arr.filter(function(val){ return val!==undefined; }); 
 
    console.log(updated);

+0

這是使用一個框架(未包含在項目其他原因)時的一個很好的例子是多餘。 – Shadow

+0

很好的回答!我認爲當在代碼庫中尋找一致性時,有理由堅持使用Lodash而不是使用polyfills,您是否同意這一點? **注意:**我確實意識到這是添加了'ECMA-262',這是一個相當老的規範版本,所以實際上這不是一個polyfill,可能更像是一個「標準實現」。 –

+0

越來越多的開發者正在從Lodash /下劃線移動。瀏覽器之所以現在支持本地使用該庫的東西。除非你支持IE8,否則我懷疑過濾器需要使用polyfill。 – epascarello

33

您可以使用_.compact(array);這將刪除nullundefined''

請參見:https://lodash.com/docs/4.15.0#compact

+6

在這種情況下,您的答案是無效的,因爲問題指出需要保留空值... – Shadow

+0

正確的,我將編輯推送到該答案以解釋並正確引用文檔。 '_Compact'將刪除'false','null','0','''','undefined'和'NaN'值。 – Markus

0

你可以試試這個。

var array = [ 1, 2, 3, undefined, 0, null ]; 
var array2 = []; 
for(var i=0; i<array.length; i++){ 
    if(!(typeof array[i] == 'undefined')){ 
     array2.push(array[i]); 
    } 
} 
console.log(array2); 
16

使用lodash的最佳方式是_.without

實施例:

const newArray = _.without([1,2,3,undefined,0,null], undefined); 
相關問題