查找数组中的数字是否介于两个数字之间,并输出介于两者之间的数值

时间:2017-04-16 11:48:32

标签: javascript arrays

过去几个小时我一直试图找出如何找到2个数字之间的数组,但我不知道该往哪里去。我需要做什么? 18和20只是占位符号,随意使用你想要的任何数字。

function start() {
    var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
    var lower = 18;
    var upper = 20;

    if (need help here) {
        alert('Yes');
    } else {
        alert('No');
    }

    document.getElementById('listOfvalues').innerHTML = ('There are ' + ___ + ' numbers that are between the two numbers);
    document.getElementById('numberExist').innerHTML = numberExist;
}

我知道我没有提供太多,但如果我自己尝试这样做,我会发疯的

5 个答案:

答案 0 :(得分:2)

var lower = 18;
var upper = 20;
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
var between = array.filter(function(item) {
  return (item > lower && item < upper);
});

答案 1 :(得分:2)

var listOfvalues=[];
    for(var i=0;i<array.length;i++){
       if (array[i]>18 && array[i]<20) {
           listOfvalues.push(array[i]);           
       } 
    }


    document.getElementById('listOfvalues').innerHTML = 'There are ' + listOfvalues.length + ' numbers that are between the two numbers';

答案 2 :(得分:1)

一种方法如下:

// a changed (hopefully meaningful) name for the function,
// lower: Number, the lower-boundary,
// upper: Number, the upper-boundary,
// haystack: Array, the array of values:
function numbersBetween(lower, upper, haystack) {

  // if every value of the Array is, or can be coerced to,
  // a Number then we continue to work with that Array:
  if (haystack.every(value => Number(value))) {

    // Here we use Array.prototype.filter() to filter the
    // values of the Array according the function:
    return haystack.filter(

      // here we use an Arrow function, since we don't need
      // to use a 'this'; here we retain the current value ('n')
      // in the Array if that Number is greater than the
      // lower-boundary and lower than the upper-boundary:
      n => n > lower && n < upper
    );
  }

  // otherwise, if not every value is, or can be coerced,
  // to a Number we simply return an empty Array:
  return [];
}

// this caches the element with the id of 'output':
let list = document.getElementById('output'),

  // we create an <li> element:
  li = document.createElement('li'),

  // we create a document fragment:
  fragment = document.createDocumentFragment(),

  // and an empty uninitialised variable:
  clone;

// we call the numbersBetween function, passing in the relevant
// boundaries and the Array:
numbersBetween(7, 20, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15])

// because the function returns an Array (either an empty Array or
// an Array with values), we can chain the function using
// Array.prototype.forEach():
.forEach(

  // here we use another Arrow function expression:
  num => {

    // clone the created <li> element and assign it
    // the 'clone' variable:
    clone = li.cloneNode();

    // set the clone's textContent to be equal to
    // the current Array-element of the Array over
    // which we're iterating:
    clone.textContent = num;

    // and append that cloned-element to the
    // document.fragment:
    fragment.appendChild(clone);
  });

// this could be used in the last iteration of the
// Array.prototype.forEach() method, but because it
// generates no errors (an empty document fragment
// can be appended to an element without consequence),
// we perform this step here, appending the document
// fragment to the cached 'list' element which appends
// the nodes contained within the document fragment to
// the specified parent-node (list):
list.appendChild(fragment);

&#13;
&#13;
function numbersBetween(lower, upper, haystack) {
  if (haystack.every(value => Number(value))) {

    return haystack.filter(
      n => n > lower && n < upper
    );
  }
  return [];
}

let list = document.getElementById('output'),
  li = document.createElement('li'),
  fragment = document.createDocumentFragment(),
  clone;

numbersBetween(7, 20, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15]).forEach(
  num => {
    clone = li.cloneNode();
    clone.textContent = num;
    fragment.appendChild(clone);
  });
list.appendChild(fragment);
&#13;
#output::before {
  content: 'The following numbers were found:';
  display: list-item;
  list-style-type: none;
}

#output:empty::before {
  content: '';
}
&#13;
<ul id="output"></ul>
&#13;
&#13;
&#13;

JS Fiddle demo

答案 3 :(得分:0)

为Wei的回答提供过滤后的解决方案

var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20];
var lower = 18;
var upper = 20;

var result = array.filter(function(item) {
  return item >= lower && item <= upper;
});

document.getElementById('listOfvalues').innerHTML = ('There are ' + result.length + ' numbers that are between the two numbers);

简而言之,使用filter function根据您的低边界和高边界返回结果。打印返回的值数组的长度。

对于if / else语句,您可以自己完成。

编辑:添加了过滤器

的链接

答案 4 :(得分:0)

您可以测试,如果该值在给定范围内并计算它。

&#13;
&#13;
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20],
    lower = 18,
    upper = 20,
    result = array.reduce(function (r, a) {
        return r + (a >= lower && a <= upper);
    }, 0);

console.log(result);
&#13;
&#13;
&#13;

ES6

&#13;
&#13;
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20],
    lower = 18,
    upper = 20,
    result = array.reduce((r, a) => r + (a >= lower && a <= upper), 0);

console.log(result);
&#13;
&#13;
&#13;

  

Array#reduce在这种情况下如何运作?

     

您有一个结果的累加器,表示为r和迭代的实际值,表示为a。如果值在给定范围内,则返回的结果是前一个计数和ckeck的总和。

    r       a   return   comment
------  ------  ------  --------
    0      18       1   in range
    1      23       1
    1      20       2   in range
    2      17       2
    2      21       2
    2      18       3   in range
    3      22       3
    3      19       4   in range
    4      18       5   in range
    5      20       6   in range
    6                   result

一些想法,都是ES6风格。

您可以使用Array#reduce的回调,其关闭超过lowerupper,例如

&#13;
&#13;
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20],
    getCountInRange = (lower, upper) => (r, a) => r + (a >= lower && a <= upper);

console.log(array.reduce(getCountInRange(18, 20), 0));
&#13;
&#13;
&#13;

或者您可以使用一个函数来获取数组lowerupper并返回计数。

&#13;
&#13;
var array = [18, 23, 20, 17, 21, 18, 22, 19, 18, 20],
    getCountInRange = (array, lower, upper) => array.reduce((r, a) => r + (a >= lower && a <= upper), 0);

console.log(getCountInRange(array, 18, 20));
&#13;
&#13;
&#13;