两个值之间的结果数组 - javascript

时间:2015-11-18 14:05:10

标签: javascript arrays numbers between

我想知道是否有办法让一个数组的最小值和最大值得到另一个数组,或类似的东西:

var numbers = ['10','15','20','25','30','35','40','45','50'];  

var getnumbers = function(min,max){
 //return a result that is push to another array, in this case "results"
};
getnumbers(10,30);
console.log(results);

输出应该给我一些像10 - 15 - 20 - 25 - 30

4 个答案:

答案 0 :(得分:2)

略有不同的方法,具有用于过滤的自定义回调函数。

function filterNumbers(min, max) {
    return function (a) { return a >= min && a <= max; };
}

var numbers = ['10', '15', '20', '25', '30', '35', '40', '45', '50'],
    result = numbers.filter(filterNumbers(10, 30));

document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');

答案 1 :(得分:0)

您可以执行以下操作:numbers.filter(function (value) { return value >= 10 && value <= 30 });

如果您确实希望输出为N1 - N2 - N3 ... - NN,请执行numbers.filter(function (value) { return value >= 10 && value <= 30 }).join(' - ');

答案 2 :(得分:0)

试试这个

var numbers = ['10','15','20','25','30','35','40','45','50'];  
var output = "";
var getnumbers = function(min,max){
  for (var i = 0; i < numbers.length; i++){
    if(numbers[i] >= min && numbers[i] <= max){
      output += numbers[i] + "-";
    }
  }
};
getnumbers(10,30);
console.log(output);

答案 3 :(得分:0)

JavaScript具有内置功能来解决此问题。

let numbers = ['10','15','20','25','30','35','40','45','50'];
// Get all elements between '10' and '30'
let result = numbers.splice(numbers.indexOf('10'),numbers.indexOf('30') + 1);
console.log(result);
// If you want the answer to literally be '10-15-20-25-30'
let resultString = "";
for(const i in result){
    resultString.concat(`${result[i]}-`)
}
console.log(resultString);