function largerNum (a,b){
if (a>b){
console.log("The larger number of " +a, "and " +b, "is " +a,".");
}
else{
console.log("The larger number of " +a, "and " +b, "is " +b,".");
}
}
console.log(largerNum (5,12));
输出显示 - 6和12的较大数字是12 未定义
答案 0 :(得分:0)
因为你的函数没有返回,所以console.log(largerNum (5,12))
给出了未定义的
让你的函数返回一些东西
chnage to
function largerNum (a,b){
if (a>b){
return "The larger number of " + a + " and " + b + " is " + a + "."
}
else{
return "The larger number of " + a + " and " + b + " is " + b + "."
}
}
console.log(largerNum (5,12));
答案 1 :(得分:0)
这是因为该函数没有显式返回任何内容,它默认返回undefined
function largerNum(a, b) {
if (a > b) {
console.log("The larger number of " + a, "and " + b, "is " + a, ".");
} else {
console.log("The larger number of " + a, "and " + b, "is " + b, ".");
}
// this function is not returning anything
}
console.log(largerNum(5, 12));
答案 2 :(得分:0)
您没有从largerNum
函数返回任何值,因此返回了undefined
的默认返回值。您可以像这样重构代码。
注意:该字符串与
+
连接,而不是使用,
将参数分隔为console.log
function largerNum(a, b) {
if (a > b) {
return "The larger number of " + a + " and " + b + " is " + a + "."
}
else {
return "The larger number of " + a + " and " + b + " is " + b + "."
}
}
console.log(
largerNum(5, 12)
)
console.log(
largerNum(13, 42)
)
答案 3 :(得分:0)
您的larger()
函数没有返回任何值,因此您将null
传递给最后一个console.log()
语句。
function largerNum (a,b){
if (a>b){
return a;
} else {
return b;
}
}
console.log(
"The larger number of " + a + ", and " + b + ", is " +
largerNum(a,b) + "."
);
应该工作
答案 4 :(得分:0)
因为您在调用函数时不需要console.log
:您的函数不返回任何内容,并且您会看到其他undefined
。只需从console.log()
中删除console.log(largerNum (5,12))
包装:
function largerNum (a,b){
if (a>b){
console.log("The larger number of " +a, "and " +b, "is " +a,".");
}
else{
console.log("The larger number of " +a, "and " +b, "is " +b,".");
}
}
largerNum(5,12);

或者从函数返回值并记录函数调用:
function largerNum (a,b){
if (a>b){
return "The larger number of " +a+ " and " +b+ " is " +a+ ".";
}
else{
return "The larger number of " +a+ " and " +b+ " is " +b+ ".";
}
}
console.log(largerNum(5,12));