断言范围错误

时间:2017-07-03 12:33:45

标签: javascript function range

我正在编写一个rangeAssertion函数,类似于有人说“给我1到5之间的数字”。您认为可能的答案是“1,2,3,4或5”。即,您通常不会将选项解释为“2,3或4”。

假设“实际”和“预期”参数始终是数字(例如,不是布尔值或在检查“范围”的上下文中没有意义的其他类型。)

以下是传递的样本:

var sas = 20;
rangeAssertion(4, 21, sas, 'blackjack score should be between 4 and 21');
// console output:
// passed

以下示例失败:

var price = 101;
rangeAssertion(1, 100, price, 'price should be between 1 and 100');
// console output:
// FAIL [price should be between 1 and 100] "101" not within range 1 to 100

到目前为止,这是我得到的:

function rangeAssertion(low, high, actual, testName) {
  if(low === high){
   onsole.error( "FAIL [" + testName + "] Expected \"" + expected + ", \" but got \"" + actual + "\"");
}else{
console.info( "SUCCESS [" + testname + "]");
}
}

知道我在这里缺少什么吗?请帮忙!

1 个答案:

答案 0 :(得分:0)

您应该比较实际值是否介于高位和低位之间:

function rangeAssertion(low, high, actual, testName) {
  if(low <= actual && actual <= high){
    console.error( "FAIL [" + testName + "] Expected \"" + expected + ", \" 
  but got \"" + actual + "\"");
  }else{
    console.info( "SUCCESS [" + testname + "]");
  }
}