简体   繁体   English

如何跳出 Javascript 中的函数?

[英]How to break out of a function in Javascript?

Here is the piece of code, note I have commented of what I would like to achieve in the code这是一段代码,请注意我已经评论了我想在代码中实现的目标

const extraHot = () => {
   if (hot === "h") {
      return `extra hot`
   }
// otherwise, do nothing, don't return anything
// (not even an empty string or undefined object)
// I want to break here
}

if (givenAmount >= dict){
// I would like to return "Drink maker makes 1 extra hot sugar and 1 stick"
    return `Drink maker makes 1 ${extraHot()} sugar and 1 stick`
}

The following code will return "undefined" between "makes" and "sugar"以下代码将在“makes”和“sugar”之间返回“undefined”

const extraHot = () => {
   if (hot === "h") {
      return `extra hot`
   }
   return
}

The following code will return a space between "makes" and "sugar"以下代码将返回“makes”和“sugar”之间的空格

const extraHot = () => {
   if (hot === "h") {
      return `extra hot`
   }
   return ""
}

Your problem is not what the function returns if hot !== "h" , but how you write your template string.您的问题不在于函数在hot !== "h"返回什么,而在于您如何编写模板字符串。 In case of if evaluates to true, return ' extra hot ' , and write the template string like如果 if 评估为真,则返回' extra hot ' ,并编写模板字符串,如

Drink maker makes 1${extraHot()}sugar and 1 stick

The reason you get the space between makes and sugar is because you have one space after makes and another one in front of sugar .你的品牌之间的空间的原因是因为你有一个后空间makes和另一个在前面的sugar To prevent this you would have to change the extra hot function to:为了防止这种情况,您必须将额外的热功能更改为:

const extraHot = () => {
   if (hot === "h") {
      return "extra hot " # Note the space after hot
   }
   return ""
}

And use it later with:稍后将其用于:

if (givenAmount >= dict){
    return `Drink maker makes 1 ${extraHot()}sugar and 1 stick`
}

You could normalize functions for returning a string to return an empty string and if some result take an extra space in front of the string or at the end and keep this style.您可以将返回字符串的函数标准化为返回空字符串,如果某些结果在字符串前面或末尾占用额外的空间并保持这种样式。

This approach allowes to chain conditions and get no extra space, if the condition is wrong.如果条件错误,这种方法允许链接条件并且不会获得额外的空间。

In this case take在这种情况下取

const extraHot = () => hot === "h" ? ' extra hot' : '';

and

if (givenAmount >= dict) return `Drink maker makes 1${extraHot()} sugar and 1 stick`;

The result is either结果要么

Drink maker makes 1 sugar and 1 stick

or或者

Drink maker makes 1 extra hot sugar and 1 stick
                   ^^^^^^^^^^

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

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