简体   繁体   English

使用 if else 语句提示 javascript 的函数

[英]functions with if else statement to prompt javascript

So I have been racking my brain why this doesn't work, I am sure that I am over thinking it but after googling for a few hours I just can't find it.所以我一直在绞尽脑汁为什么这不起作用,我确定我想多了,但在谷歌搜索了几个小时后我就是找不到它。

So the main thing I am trying is to create a JavaScript function “legs” which takes animal Object and returns some custom message (String) if the animal has 0 legs, 2, 4, and one message for others.所以我尝试的主要事情是创建一个 JavaScript 函数“legs”,它接受动物对象并返回一些自定义消息(字符串),如果动物有 0 条腿、2、4 和一条消息给其他人。

My attempt:我的尝试:

var animal = prompt("Type in an animal")

function legs(animal){

    if(animal == 'fish'){
        return "no legs";
    }else if(animal == 'Tiger'){
        return "4 legs";
    }else if(animal == 'kangaroo'){
        return "2 legs";
    }else { 
        return "I don't know";
        }
}

What am I doing wrong?我究竟做错了什么?

You need to call legs function like legs(animal)你需要像legs(animal)一样调用legs函数

 var animal = prompt("Type in an animal") function legs(animal){ if(animal == 'fish'){ return "no legs"; }else if(animal == 'Tiger'){ return "4 legs"; }else if(animal == 'kangaroo'){ return "2 legs"; }else { return "I don't know"; } } console.log(legs(animal));

this way you can call the leg() function.这样你就可以调用leg()函数。

 var animal = prompt("Type in an animal") function legs(animal) { if (animal == 'fish') return "no legs"; else if (animal == 'Tiger') return "4 legs"; else if (animal == 'kangaroo') return "2 legs"; else return "I don't know"; } let result = legs(animal) console.log(result)

Just improving the answer.只是改进答案。 You to get the answer you need to call the function you have defined.您需要调用您定义的函数来获得答案。 Anyway better (cleaner) if you define it before reaching the interactive part (prompt).如果您在到达交互式部分(提示)之前定义它,无论如何会更好(更干净)。

Since you are returning in each scenario you do not need to use an else.由于您在每个场景中都返回,因此您不需要使用 else。

function legs(animal) {
  if (animal == 'fish') 
    return "no legs";
  if (animal == 'Tiger') 
    return "4 legs";
  if (animal == 'kangaroo') 
    return "2 legs";

  return "I don't know";
}

const animal = prompt("Type in an animal");

console.log(legs(animal));

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

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