为什么重新分配工作而不是仅仅在 concat 中返回?

Why does reassigning work rather than just returning in concat?

只是想弄清楚为什么重新分配有效而不是直接返回。我知道可能有更好的方法可以做到这一点,但我只是想了解一下。

给定:const anArray = [1, 'foo', 2, 'bar']

 const getConcatenatedStr = (arr) => {
      let result = ''
      if (arr && arr.length > 1) {
         arr.forEach(() => {
            return result.concat('', ' ')
         })
       } else {
         result = ''
      }
      return result.trim()
   }

console.log('result one:', getConcatenatedStr(anArray)) returns 'result one: '

 const getConcatenatedStrReassign = (arr) => {
      let result = ''
      if (arr && arr.length > 1) {
         arr.forEach(() => {
            result = result.concat('', ' ')
            return result
         })
       } else {
         result = ''
      }
      return result.trim()
   }

console.log('result two: ', getConcatenatedStrReassign(anArray)) returns result two:

当然这样也行,等于getConcatenatedStrReassign:

    // ...
      if (arr && arr.length > 1) {
            return result = result.concat('', ' ')
         })
    // ...
  1. 您不需要 return 来自 forEach
  2. 的任何内容
  3. String.concat 不修改源字符串。

所以如果你想继续添加,你需要重新赋值。

或者你也可以

const anArray = [1, 'foo', 2, 'bar']
const cools = anArray.map(() => '').join(' ') || '';

console.log(cools);

因为 returnforEach 中只是 return 你来自 forEach,而不是来自函数

forEach 将回调作为参数,并对数组和 returns undefined 的每个索引执行该回调。因此,当您在第一个示例 returns result.concat() 中进行回调时,您实际上只是 returning undefined 而不是连接。这就是第二个示例起作用的原因,您实际上是在重新分配 result。第二个例子中的 return 仍然是多余的,因为它所做的只是 return undefined。在此处查看 Array.forEach 的文档以获得更多解释。