繁体   English   中英

从数组中删除随机字符串,JavaScript

[英]Remove random strings from an array , 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\']' " 

您正在滥用两次array filter

第一个问题是调用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测试的数组元素,并且不包含在新数组中。

不过,这很容易。 这是你会做的

 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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM