使用范围值而不使用数组

时间:2018-04-05 09:02:10

标签: javascript

我遇到了这个逻辑的麻烦。我试图找到一种方法,其中单个变量将具有多个值而不使用数组。这是我的代码

var num = {
 from: 500,
 to: 700
  };
 if (num == 500 && num == 600 && num==700) { 
 console.log("working");
 }
 else { 
 console.log("not working")
 }

3 个答案:

答案 0 :(得分:1)

要访问您的对象(具有多个值的变量),您必须这样做:

var num = {
    from: 100,
    to: 300
}

console.log(num.from); //This will print 100
console.log(num.to); //This will print 300

你可以这样做

num.from += 1;
console.log(num.from); //This will print 101

所以你的(Ryan Arellano)代码必须是这样的:

function check(num, value) {
    return num.from <= value && value <= num.to;
}

var num = { from: 100, to: 300 };

if (check(num, 500) && check(num, 600) && check(num, 700)) {
    console.log("working");
} else {
    console.log("not working")
}

console.log(check(num, 200));

答案 1 :(得分:1)

您可以使用函数来检查范围。

&#13;
&#13;
function check({ from, to }, value) {
    return from <= value && value <= to;
}

var num = { from: 100, to: 300 };

if (check(num, 500) && check(num, 600) && check(num, 700)) {
  console.log("working");
} else {
  console.log("not working")
}

console.log(check(num, 200));
&#13;
&#13;
&#13;

答案 2 :(得分:1)

使用函数并尝试比较值。

&#13;
&#13;
var num = {
 from: 100,
 to: 300,
 checkValue:function(num){
  return this.from <= num && num <= this.to
 }
};
console.log('1st check');
if (num.checkValue(100) && num.checkValue(600) && num.checkValue(700)) { 
 console.log("working");
}
else { 
 console.log("not working")
}

console.log('2nd check');
if (num.checkValue(120) && num.checkValue(150) && num.checkValue(250)) { 
 console.log("working");
}
else { 
 console.log("not working")
}
&#13;
&#13;
&#13;