我正在进行Codecademy JS培训,作为我即将开始的课程的评论。我点击了creditCheck函数练习,它基本上只需要一个计算整数的函数,并返回一个大于100的值,下面一个值。我认为下面的代码应该可以正常工作,但它在没有被调用的情况下运行。为什么会这样?
creditCheck = function(income)
{
income *= 1; // one way to convert the variable income into a number.
if (income>100)
{
console.log("You earn a lot of money! You qualify for a credit card.");
return true; // this is an actual return value, console.log() always returns "undefined"
}
else
{
console.log("Alas you do not qualify for a credit card. Capitalism is cruel like that.");
return false;
}
};
console.log("If the log is executing in the function def then this should print second. Otherwise it's probably being executed by the coding script itself.\n\n")
决议(可能): 所以我只是在Codecademy网站的控制台上测试了脚本。除了在该网站上,它不会自行执行任何地方。这让我相信这个页面有一些时髦的东西。
更多决议(也许): 我还添加了上面的最后一行来测试函数被调用的时间。由于它是程序中的最后一行,我的假设是如果执行在函数体本身中,那最后一行将打印到最后一行。这让我相信评分脚本会自动调用函数,这意味着当我添加实际的函数调用时,它会搞砸它。
答案 0 :(得分:3)
您必须调用已定义的功能。
var creditCheck = function(income)
{
if (income>100)
{
return(console.log("You earn a lot of money! You qualify for a credit card."));
}
else
{
return(console.log("Alas you do not qualify for a credit card. Capitalism is cruel like that."));
}
}; creditCheck(111);
答案 1 :(得分:0)
你必须调用函数来调用它;)
creditCheck = function(income)
{
income *= 1; // one way to convert the variable income into a number.
if (income>100)
{
console.log("You earn a lot of money! You qualify for a credit card.");
return true; // this is an actual return value, console.log() always returns "undefined"
}
else
{
console.log("Alas you do not qualify for a credit card. Capitalism is cruel like that.");
return false;
}
};
var check = creditCheck(123); // runs the function
alert(check); // and alerts() the result
答案 2 :(得分:0)
正如其他回答者所指出的那样,函数声明中的语法本身有点偏,你需要调用函数。下面是应该纠正这两个问题的代码。只需将此代码复制到新的.html文件,然后在浏览器中打开:
<html>
<body>
<h1>Credit Check Example</h1>
<script>
function creditcheck(income)
{
if (income>100)
{
alert("You earn a lot of money! You qualify for a credit card.");
}
else
{
alert("Alas you do not qualify for a credit card. Capitalism is cruel like that.");
}
}
creditcheck(1000);
</script>
</body>
</html>
答案 3 :(得分:0)
没有人投票是正确的,所以我想我会对此进行排序。
问题是你需要重新阅读这个问题。 if大于或等于100.因此符号为'&lt; =',NOT'&lt;'。
creditCheck = function(income){
if(income>=100){
return "You earn a lot of money! You qualify for a credit card.";
} else{
return "Alas you do not qualify for a credit card. Capitalism is cruel like that.";
}
};
creditCheck(75);
creditCheck(125);
creditCheck(100);
答案 4 :(得分:0)
实际的解决方案与我在提交的代码中调用我自己的函数以及分级函数解释它的方式有关。另外,该脚本期待console.log(#whatever)的其他一些安排,所以当我没有调用我自己的函数时,这会使它变得复杂。