简体   繁体   English

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

[英]Remove random strings from an array , JavaScript

I need to remove strings from an array and i have this function; 我需要从数组中删除字符串,我有此功能; It makes some random tests and returns a result. 它进行一些随机测试并返回结果。

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

When i don't return anything i get undefined (obviously), but when i return the array i get this: 当我不返回任何东西时,我变得不确定(很明显),但是当我返回数组时,我得到了这个:

"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\']' " 

You are misusing twice the array filter . 您正在滥用两次array filter

The first problem is that the array doesn't change when you call 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");
}

The second problem is that you are filtering the opposite you want to filter. 第二个问题是您正在过滤要过滤的对象。

// 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 . filter()为数组中的每个元素调用一次提供的callback函数,并构造一个所有值的新数组,为此, callback返回一个强制为true的值。 callback is invoked only for indexes of the array which have assigned values; 仅对具有指定值的数组索引调用callback 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. 仅跳过未通过callback测试的数组元素,并且不包含在新数组中。

It's pretty easy though. 不过,这很容易。 Here's how you will do it 这是你会做的

 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