为什么javascript不生成函数的输出?
var name = prompt("What is your name?");
var weight = prompt("what is your weight?");
function check(name ,weight){
if (weight> 25) {
alert (name + "Your weight is " + weight + "which is not normal."+ "Sorry");
}
else {
alert (name + "Your weight is " + weight + "which is normal." + "Welcome");
}
return check;
}check;
</script>
答案 0 :(得分:1)
因为它格格不入,所以你甚至不能结束这项功能。
你必须返回一个值才能返回任何值。
也许这就是你想要实现的目标:
var name = prompt("What is your name?");
var weight = prompt("what is your weight?");
function check(name ,weight){
if (weight> 25) {
return name + "Your weight is " + weight + "which is not normal."+ "Sorry";
} else {
return name + "Your weight is " + weight + "which is normal." + "Welcome";
}
}
alert(check(name, weight));
注意我如何将参数name
和weight
传递给check
- 函数
答案 1 :(得分:1)
应该是这样的:
var name = prompt("What is your name?");
var weight = prompt("what is your weight?");
function check(name ,weight){
if (weight> 25) {
alert (name + "Your weight is " + weight + "which is not normal."+ "Sorry");
}
else {
alert (name + "Your weight is " + weight + "which is normal." + "Welcome");
}
return true; // check is invalid
} // you forgot to close it
check(name,weight); // calling the function
答案 2 :(得分:0)
声明函数时,您将声明参数:名称和重量。这些参数只能在该函数的范围内使用。看起来您正试图将它们设置在范围之外。然后你返回变量检查。哪个是空的。此外,您还没有从函数外部调用函数,因此函数check()永远不会被触发。
这是一个例子(live example):
var input1="peter"; input2=10;
check(input1, input2);
function check(name, weight) {
var check;
if (weight < 25) { //true
check = "Text"+name;
} else {
check = "No text"+name;
}
return alert(check);
}
PS:尚未测试此代码。
答案 3 :(得分:0)
该函数需要外部调用来执行操作。因此,如果您想以上述方式显示结果,请添加
function check(name ,weight){
if (weight> 25) {
alert (name + "Your weight is " + weight + "which is not normal."+ "Sorry");
}
else {
alert (name + "Your weight is " + weight + "which is normal." + "Welcome");
}
return true;
}
check(name,weight);
或者你可以通过其他方式调用它
<p id="print"></p>
<script>
function check(name ,weight){
if (weight> 25) {
alert (name + "Your weight is " + weight + "which is not normal."+ "Sorry");
}
else {
alert (name + "Your weight is " + weight + "which is normal." + "Welcome");
}
return check;
}
var name = prompt("What is your name?");
var weight = prompt("what is your weight?");
document.getElementById("print").innerHTML = check(name, weight);
</script>