2014-10-04 113 views
1

我有一個包含數字和字符串的數組,我想從數組中刪除所有字符串。 這裏是數組:從數組中刪除字符串

var numbOnly = [1, 3, "a", 7]; 

在這種情況下,我想刪除anumbOnly結果numbOnly = [1, 3, 7])。

謝謝。

+1

遍歷數組,並使用檢查的dataType'typeof' – Praveen 2014-10-04 07:10:57

+0

我想你的意思'「一」''不A'?或者是一個包含字符串的變量? – 2014-10-04 07:18:05

+0

是的,我的意思是「a」。 – 2014-10-04 07:19:16

回答

2

你可以使用這個:

var numbOnly = [1, 3, "a", 7]; 
var newArr = numbOnly.filter(isFinite) // [1, 3, 7] 

上述作品真的很好,如果你沒有像字符串數組中"1"。爲了克服這一點,你可以過濾數組是這樣的:

newArr = numbOnly.filter(function(x){ 
    return typeof x == "number"; 
}); 
+0

我想要'.filter(isFinite)'。 'Number'會過濾掉零。 – elclanrs 2014-10-04 07:30:23

+0

@elclanrs謝謝! – 2014-10-04 07:32:42

3

可以使用Array.prototype.filter功能與Object.prototype.toString沿着這樣

var array = [1, 3, 'a', 7]; 

var numbOnly = array.filter(function(currentItem) { 
    return Object.prototype.toString.call(currentItem).indexOf('Number')!==-1; 
}); 

console.log(numbOnly); 
# [ 1, 3, 7 ] 

或者,您可以使用typeof檢查類型這樣

return typeof currentItem === 'number'; 

filter功能將保留在當前元素只有傳遞給它的函數返回當前項目的true。在這種情況下,我們正在檢查當前項目的類型是否爲數字。因此,filter將只保留類型爲數字的項目。