使用 JavaScript 检查输入数字是否在范围内

检查输入是否在数组范围内。假设,如果输入值为 12,答案应该是球。


var ranges = [{"1-10":"Apple"},{"11-20":"Ball"},{"21-30":"Cat"}]

var input_number = 12;

var get_answer = ...  // should be "Ball"


HUH函数
浏览 623回答 3
3回答

MMMHUHU

简单的代码给你var ranges = [{"1-10":"Apple"},{"11-20":"Ball"},{"21-30":"Cat"}]function getAns(input_number) {&nbsp; let result = null&nbsp; // handle input ranges&nbsp; for (let index in ranges) {&nbsp; &nbsp; for (let key in ranges[index]) {&nbsp; &nbsp; &nbsp; let min = key.split('-')[0]&nbsp; &nbsp; &nbsp; let max = key.split('-')[1]&nbsp; &nbsp; &nbsp; if (input_number >= min && input_number <= max) {&nbsp; &nbsp; &nbsp; &nbsp; result = ranges[index][key]&nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; }&nbsp; return result}console.log(getAns(12))

千巷猫影

我会使用过滤器const getValue = (value, ranges) => {&nbsp; const res = ranges.filter(obj => {&nbsp; &nbsp; const [min, max] = Object.keys(obj)[0].split("-");&nbsp; &nbsp; return value >= +min && value <= +max;&nbsp; })&nbsp; return res && res.length > 0 ?&nbsp; Object.values(res[0])[0] :&nbsp; "N/A"}const ranges = [{"1-10":"Apple"},{"11-20":"Ball"},{"21-30":"Cat"}]console.log(getValue(0,ranges))console.log(getValue(1,ranges))console.log(getValue(12,ranges))console.log(getValue(30,ranges))console.log(getValue(31,ranges))

有只小跳蛙

尝试ranges.map(x=>&nbsp;Object.entries(x).flat()&nbsp;) &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;.find(a=>&nbsp;(a[0]=a[0].split`-`,&nbsp;n>=a[0][0]&nbsp;&&&nbsp;n<=a[0][1]&nbsp;&&&nbsp;a[1])&nbsp;)var ranges = [{"1-10":"Apple"},{"11-20":"Ball"},{"21-30":"Cat"}]var n=12;var r = ranges.map( x=>Object.entries(x).flat() )&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .find(a=> (a[0]=a[0].split`-`, n>=a[0][0] && n<=a[0][1] && a[1]) )console.log(r[1]);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript