简体   繁体   English

如何使用 function 和两个参数 javaScript 进行字符串插值

[英]How to do string interpolation with function with two parameters javaScript

I am a complete newbie.我是一个完整的新手。 But I am working on a piece of training code and hit a wall.但是我正在编写一段培训代码并碰壁。 I completed the project, however, I wanted to test an additional piece of code.我完成了这个项目,但是,我想测试一段额外的代码。 I want to use string interpolation to show the user a message like this:我想使用字符串插值向用户显示这样的消息:

If this object were on ${planetName} it would weight ${thisMuch}.

But I am confused on how to call only one argument from a function with two parameters.但是我很困惑如何只用两个参数从 function 中调用一个参数。

    function calculateWeight(earthWeight, planet) {
let weight;
if(planet === 'Mercury') {
weight = earthWeight * .378
return `${weight}`
}if(planet === 'Venus') {
weight = earthWeight * .907
return `${weight}`
}if(planet === 'Mars') {
weight = earthWeight * .377
return `${weight}`
}if(planet === 'Jupiter') {
weight = earthWeight * 2.36
return `${weight}`
}if(planet === 'Saturn') {
weight = earthWeight * 0.916
return `${weight}`
} else {
return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.'
   }
}


// Uncomment the line below when you're ready to try out your function
 console.log(calculateWeight(100, 'Jupiter')) 

Couple of changes:几个变化:

First there is a difference in the way you have written multiple if s and if , else-if .首先,您编写多个if s 和ifelse-if的方式有所不同。 The first one will run all planet conditions even if the 1st one is satisfied.即使满足第一个条件,第一个条件也会运行所有行星条件。 You do not want that.你不希望出现这种情况。

Second, try to return your statement from inside the function.其次,尝试从 function 内部返回您的语句。 You are returning only weight for a planet.你只返回一个星球的weight

With the statement in place all you need is the weight value and your job can be done with a single return statement.有了声明,您所需要的只是重量值,您的工作可以通过一个return声明来完成。

 function calculateWeight(earthWeight, planet) { let weight; if(planet === 'Mercury') { weight = earthWeight *.378 }else if(planet === 'Venus') { weight = earthWeight *.907 }else if(planet === 'Mars') { weight = earthWeight *.377 }else if(planet === 'Jupiter') { weight = earthWeight * 2.36 }else if(planet === 'Saturn') { weight = earthWeight * 0.916 } else { return 'Invalid Planet Entry. Try: Mercury, Venus, Mars, Jupiter, or Saturn.' } return `If this object were on ${planet} it would weight ${weight}.` } // Uncomment the line below when you're ready to try out your function console.log(calculateWeight(100, 'Jupiter'))

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

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