SORU
11 Kasım 2008, Salı


Javascript içinde bir dizi boş öğeleri kaldırın

Nasıl JavaScript bir dizi boş öğeler kaldırabilirim?

Basit bir yolu var, ya aracılığıyla döngü ve onlara el kaldırmak için gerekir mi?

CEVAP
16 Mayıs 2010, Pazar


Saf javascript:

var arr = [1,2,,3,,3,null,,0,,undefined,4,,4,,5,,6,,,,];

// (filter - JS 1.6 and above)
arr = arr.filter(function(n){ return n != undefined }); 

arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]

//or - (only for arrays items which are numbers is numbers' strings)**
arr = arr.filter(Number) // [1, 3, 3, 4, 4, 5, 6]

// ES6 style (Firefox FTW)
arr.filter(n => true) // [1, false, 3, 3, null, 0, undefined, 4, 4, 5, 6]

ya da - (sadecetekdizi öğeleri türü "") metin

['','1','2',3,,'4',,undefined,,,'5'].join('').split(''); 
// output:  ["1","2","3","4","5"]

veya Klasik yol: basit yineleme

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

arr // [1,2,3,3,[],Object{},5,6]

jQuery ile:

var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];

arr = $.grep(arr,function(n){ return(n) });

arr // [1, 2, 3, 3, 4, 4, 5, 6]

GÜNCELLEME, daha hızlı, daha serin başka bir yolu (ES6 kullanarak):

var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,], 
    temp = [];

for(let i of arr)
    i && temp.push(i); // copy each non-empty value to the 'temp' array

arr = temp;
delete temp; // discard the variable

arr // [1, 2, 3, 3, 4, 4, 5, 6]

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • AutoklubZAPRESIC

    AutoklubZAPR

    17 Mayıs 2011
  • pilslajt

    pilslajt

    20 HAZİRAN 2008
  • Pocketnow

    Pocketnow

    14 EKİM 2007