本文介绍了如何过滤大于x的数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在Internet上四处浏览,即使我确定这是一个非常简单的修复程序,也找不到任何有关如何解决此问题的帖子.

I've been looking around on the internet and I cant find any posts that cover how to fix this even though I am certain it is a very simple fix.

基本上,我有一个带有数字值的数组,我想过滤掉大于10的任何数字并将它们添加到另一个数组中.到目前为止,这是我得到的,但是我得到的是第一个数组中的所有数字.

Basically I have an array with number values in it and I want to filter out any numbers that are greater than 10 and add them into another array. Here's what I have so far but what I am getting is all of the numbers from the first array.

<!DOCTYPE html>
<html>
<body>
  <p id="demo"></p>
  <button type="button" onclick="alert(output)">Click Me!</button>
  <script>
    var input = new Array(9,3,4.3,24,54,8,19,23,46,87,3.14);
    var output = new Array();
    var length = 1;
    for (var i = 0; i < input.length; i += length) {
      output.push(input.slice(i, i + length).join(" "));
    }
  </script>
</body>
</html>

推荐答案

function predicate(x) { return x > 10 }
var output = input.filter(predicate);
input = input.filter(function(x) { return !predicate(x) })

使用ES6箭头功能看起来更干净:

Looks even cleaner with ES6 arrow functions:

var predicate = (x) => x > 10;
var output = input.filter(predicate);
input = input.filter(x => !predicate(x));

这篇关于如何过滤大于x的数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

11-03 09:29