简体   繁体   English

返回true或返回false

[英]Return true or Return false

I am learning Javascript, and I am trying to go over everything I have learned so far. 我正在学习Javascript,我试图回顾到目前为止我所学到的一切。 I am trying to figure out how to get a message back like an alert box when using the return statement. 我正在尝试弄清楚如何在使用return语句时将消息恢复为警告框。 alert(Example(2,3)); works, also making a gobal variable like this works. 工作,也像这样工作的gobal变量。 var sum = Example(2,3); alert(sum); . But I bet there are better ways then I can think of. 但我敢打赌,有更好的方法可以让我想到。

function Example(x, y) {

    if (x * y === 108) {

        return true;

    } else {

        return false;

    }

}
Example(2, 3);

Your function can be a lot simpler. 你的功能可以简单得多。 Just return the boolean you get from the comparison: 只需返回从比较中得到的布尔值:

function example(x, y) {
    return (x * y === 108);
}

As for how to make the alert box, I'd recommend not using alert boxes at all . 至于如何制作警报框,我建议不要使用警报框

  • If you want to show something to the user, use plain HTML, jQuery or similar. 如果要向用户显示内容,请使用纯HTML,jQuery或类似内容。
  • If you want to debug, use console.log or similar. 如果要调试,请使用console.log或类似的。

Alerts are highly annoying and prevent interaction with the page. 警报非常烦人并且阻止与页面的交互。

If for some reason you have to use an alert (for example, you're forced to debug on a system with no developer tools) then this will work just fine: 如果由于某种原因你必须使用警报(例如,你被迫在没有开发人员工具的系统上调试)那么这将正常工作:

alert(example(2,3));

Have it this way, :) 有这样的方式,:)

function Example(x, y) {
    return x * y === 108; 
}
Example(2, 3);

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

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