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

Remove random strings from an array , JavaScript

我需要从数组中删除字符串,我有这个功能; 它会进行一些随机测试并 return 结果。

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

当我不 return 任何东西时我得到未定义的(很明显),但是当我 return 数组时我得到这个:

"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 的两倍。

第一个问题是调用过滤器时数组没有改变。

// 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() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. callback is invoked only for indexes of the array which have assigned values; it is not invoked for indexes which have been deleted or which have never been assigned values. Array elements which do not pass the callback test are simply skipped, and are not included in the new array.

虽然这很容易。以下是您的操作方式

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