简体   繁体   English

Array.map()中的箭头函数VS普通函数

[英]Arrow function VS normal function in Array.map()

I was solving some JS challenges and noticed that when using arrow function the result comes as expected, when i try same code using normal function it doesn't. 我正在解决一些JS挑战,并注意到当使用箭头功能时,结果如预期的那样,当我使用正常功能尝试相同的代码时却没有。 Can someone explain the difference or i might have a typo!! 有人可以解释差异,否则我可能有错字!!

here is the first solution (works): 这是第一个解决方案(有效):

function titleCase(str) {
    str = str.split(' ').map(i =>  i[0].toUpperCase() + i.substr(1).toLowerCase()).join(' ')
    return str;
  }
   console.log(titleCase("I'm a liTTle tea pot")); // I'm A Little Tea Pot

And the second solution with normal function (returns empty string): 第二种具有正常功能的解决方案(返回空字符串):

function titleCase2(str) {
    str = str.split(' ').map(function(i, index){ i[0].toUpperCase() + i.substr(1).toLowerCase()}).join(' ')
    return str;
  }
   console.log(titleCase2("I'm a liTTle tea pot")); // empty string

我的控制台的屏幕截图

You can use My Plunker here 您可以在此处使用“我的柱塞”

You miss a return keyword inside the callback function. 您会在回调函数中错过return关键字。

Fat-arrow function returns a value by default, the return keyword is built-in. Fat-arrow函数默认情况下返回值, return关键字是内置的。 To get the value from the normal function expression, you have to return it. 要从普通函数表达式中获取值,您必须将其返回。

 function titleCase2(str) { str = str.split(' ').map(function(i, index) { return i[0].toUpperCase() + i.substr(1).toLowerCase() }).join(' ') return str; } console.log(titleCase2("I'm a liTTle tea pot")); 

You need explicit return for non-arrow functions. 您需要显式return非箭头函数。 1-line arrow functions implicitly return the result of that one line. 1行箭头功能隐式返回该行的结果。

function titleCase2(str) {
  return str.split(' ').map(function(i, index){ return i[0].toUpperCase() + i.substr(1).toLowerCase()}).join(' ')
}
console.log(titleCase2("I'm a liTTle tea pot")); // I'm A Little Tea Pot

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

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