2017-11-25 320 views
0

我需要從數組中刪除字符串,我有這個功能; 它進行一些隨機測試並返回結果。從數組中刪除隨機字符串,JavaScript

function filter_list(array) { 
array.filter((elem) => typeof elem === "string"); 
return (array); 
} 

當我不回什麼,我得到了一個未定義(明顯),但是當我返回數組我得到這個:

"Expected: '[1, 2]', instead got: '[1, 2, \'a\', \'b\']' 
Expected: '[1, 0, 15]', instead got: '[1, \'a\', \'b\', 0, 15]' 
Expected: '[1, 2, 123]', instead got: '[1, 2, \'aasf\', \'1\', \'123\', 
123]' 
Expected: '[]', instead got: '[\'a\', \'b\', \'1\']' 
Expected: '[1, 2]', instead got: '[1, 2, \'a\', \'b\']' " 
+0

如果你的數字不包括+/-無窮大,你可以使用'array.filter(Number.isFinite)'。如果你的數字都是整數,使用'array.filter(Number.isInteger)'。 –

回答

0

雖然這很容易。這裏是你會怎麼做

let data = [ 
 
    "Cat", 
 
    1451, 
 
    14.52, 
 
    true, 
 
    "I will be removed too :(" 
 
]; 
 

 

 
let filteredData = data.filter(item => typeof item !== "string"); 
 

 
console.log(filteredData); // or return it

+0

非常感謝! –

2

您濫用array filter兩次。

第一個問題是當您調用過濾器時,數組不會更改。

// This code isn't the correct yet, continue below 
function filter_list(array) { 
    // You have to return the result of filter. The 'array' is not changed. 
    return array.filter((elem) => typeof elem === "string"); 
} 

第二個問題是您正在過濾您要過濾的對象。

// Correct code 
function filter_list(array) { 
    // If the condition is true, the element will be kept in the NEW array. 
    // So it must be false for strings 
    return array.filter((elem) => typeof elem !== "string"); 
} 

filter()調用每個元件在一個 提供callback函數數組一次,並構建所有的值的一個新的數組, callback返回到強制轉換true的值。 callback被調用 僅適用於已分配值的數組索引;不是 對已被刪除的索引或從未被分配的值的索引調用。未通過callback測試 的數組元素會被略過,並且不包含在新數組中。

+0

我明白了!非常感謝您的幫助!! –