简体   繁体   English

为什么函数返回布尔值?

[英]Why function returns boolean value?

I am writing my own function which returns lower argument between two arguments. 我正在编写自己的函数,该函数在两个参数之间返回较低的参数。

My first solution was: 我的第一个解决方案是:

function min(a, b) {
  if (a < b)
    return a;
  else
    return b;
}

console.log(min(0, 10));
// → 0

But I wanted to simplify it and wrote another one function: 但是我想简化它,并编写了另一个函数:

function min(a, b) {
   return a ? a < b : b;
}
console.log(min(0, 10));
// → true

Why my second function returns boolean value instead of number? 为什么我的第二个函数返回布尔值而不是数字? Can I change this behavior? 我可以改变这种行为吗?

It should be 它应该是

function min(a, b) {
   return a < b ? a : b;
}
console.log(min(0, 10));

Your ternary operater is a little funky. 您的三元操作员有点时髦。

It should be boolean ? returnValueForTrue : returnValueForFalse; 应该是boolean ? returnValueForTrue : returnValueForFalse; boolean ? returnValueForTrue : returnValueForFalse;

So yours is doing a ? boolean : b 所以你在做什么a ? boolean : b a ? boolean : b and I'm not sure what that actually turns into. a ? boolean : b ,我不确定实际上会变成什么。 a ? boolean a ? boolean would turn into a boolean. a ? boolean将变成布尔值。

So yours should be 所以你应该

return a < b ? a : b;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM