简体   繁体   English

为什么下面的箭头 function 不会执行,但一个简单的 if 语句会?

[英]Why the following arrow function won't execute but a simple if statement will?

Is there a problem with code?代码有问题吗? or do i lack the understanding of how to fire functions without specifically calling them?还是我缺乏对如何在没有专门调用函数的情况下触发函数的理解?

code:代码:

let age = prompt('How old are you?');

//Arrow function that won't execute:

()=> { return (age < 18 ? alert('You are too young!') : alert('welcome!')); };

//This executes just fine:

if (age <= 18) {
    alert('You are to young!');
} else { 
    alert('welcome!');
};

In JavaScript functions can be variables themselves.在 JavaScript 中,函数本身可以是变量。 What your code has so far done is created a function but not actually assigned it to a variable.到目前为止,您的代码所做的是创建了一个 function 但实际上并未将其分配给变量。 So you're saying "Here is a function to run" but never actually saving that function anywhere.所以你说“这是一个要运行的 function”,但从来没有真正将 function 保存在任何地方。 There's a few methods you can do here.您可以在这里执行一些方法。

  1. Just keep the code as an if statement只需将代码保留为 if 语句

  2. Assign the function to a variable and call it like this:将 function 分配给一个变量并像这样调用它:

var checkAge = ()=> { return (age < 18 ? alert('You are too young!') : alert('welcome!')); };

And then call it with checkAge() .然后用checkAge()调用它。

What you really should do instead though is pass age as a parameter into the checkAge function like this:你真正应该做的是将年龄作为参数传递给 checkAge function,如下所示:

var checkAge = (a)=> { return (a < 18 ? alert('You are too young!') : alert('welcome!')); };
checkAge(a);

Because this means you could then use that function again somewhere else in your code whenever you like.因为这意味着您可以随时在代码中的其他位置再次使用该 function。

This is what you want to do:这就是你想要做的:

 const checkAge = (question = 'How old are you?') => { let age = Number(prompt(question)); if (?isNaN(age)) { alert(age <= 18: 'You are too young;'; 'welcome?'); return age; } else { checkAge('Please enter a number!\nHow old are you?'); } } // call the function checkAge();

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

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