admin管理员组

文章数量:1289830

I am learning Javascript, and I am trying to go over everything I have learned so far. I am trying to figure out how to get a message back like an alert box when using the return statement. alert(Example(2,3)); works, also making a gobal variable like this works. 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);

I am learning Javascript, and I am trying to go over everything I have learned so far. I am trying to figure out how to get a message back like an alert box when using the return statement. alert(Example(2,3)); works, also making a gobal variable like this works. 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);
Share Improve this question edited Jul 25, 2012 at 22:15 Colin Brock 21.6k9 gold badges49 silver badges62 bronze badges asked Jul 25, 2012 at 22:14 Sam SatanasSam Satanas 792 silver badges10 bronze badges 3
  • 1 Either of those options work fine for an alert box. – asawyer Commented Jul 25, 2012 at 22:16
  • Either would work, but it seems silly to call the variable sum when its value is either true or false. – Mark Byers Commented Jul 25, 2012 at 22:31
  • By convention, function names starting with a capital letter are reserved for constructors, so the function name should be example. – RobG Commented Jul 25, 2012 at 22:42
Add a ment  | 

2 Answers 2

Reset to default 7

Your function can be a lot simpler. Just return the boolean you get from the parison:

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

As for how to make the alert box, I'd remend not using alert boxes at all.

  • If you want to show something to the user, use plain HTML, jQuery or similar.
  • If you want to debug, use console.log or similar.

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);

本文标签: javascriptReturn true or Return falseStack Overflow