简体   繁体   English

如何打印出过滤的元素?

[英]How to print out filtered elements?

How do I print out the filtered elements from the array?如何从数组中打印出过滤后的元素?
I tried console.log('randomNumbers/smallNumbers');我试过 console.log('randomNumbers/smallNumbers');
But they didn't work.但他们没有工作。
Please advise, much thanks!请指教,万分感谢!

const randomNumbers = [375, 200, 3.14, 7, 13, 852];

const smallNumbers = randomNumbers.filter(num => {
  return num < 250;
});

It's not the logging you have troubles with - but Array.filter function.这不是您遇到麻烦的日志记录 - 而是Array.filter函数。 You seem to think it somehow consumes the whole array at once, hence attempt to use length and name the argument the same way as the original array.您似乎认为它以某种方式一次消耗了整个数组,因此尝试以与原始数组相同的方式使用 length 和命名参数。

What happens instead is that the function you pass in randomNumbers.filter (as its parameter) is called once per each element of that array, taking this element as its first argument.相反,您传入randomNumbers.filter (作为其参数)的函数会针对该数组的每个元素调用一次,并将该元素作为其第一个参数。

If result of the function's call for this element is truthy, the element will stay in the result of .filter .如果该元素的函数调用结果为真,则该元素将保留在.filter的结果中。 If falsy, it gets discarded.如果为假,则将其丢弃。

So it can written as simple as this:所以它可以写成这样简单:

 const randomNumbers = [375, 200, 3.14, 7, 13, 852]; const smallNumbers = randomNumbers.filter(number => number < 250); // log the resulting array console.log(smallNumbers); // log the small numbers' ratio console.log((smallNumbers.length / randomNumbers.length).toFixed(2));

const randomNumbers = [375, 200, 3.14, 7, 13, 852];
const smallNumbers = randomNumbers.filter(number => number < 250);

// log the resulting array
console.log(smallNumbers); 

// log the small numbers' ratio
console.log((smallNumbers.length / randomNumbers.length).toFixed(2)); 

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

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