从数组中删除随机字符串,JavaScript
问题描述:
我需要从数组中删除字符串,我有这个功能; 它进行一些随机测试并返回结果。从数组中删除随机字符串,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\']' "
答
虽然这很容易。这里是你会怎么做
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
非常感谢! –
答
您滥用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
我明白了!非常感谢您的帮助!! –
如果你的数字不包括+/-无穷大,你可以使用'array.filter(Number.isFinite)'。如果你的数字都是整数,使用'array.filter(Number.isInteger)'。 –