【问题标题】:Chaining array and string methods in javascript在javascript中链接数组和字符串方法
【发布时间】:2018-10-31 09:29:53
【问题描述】:

我尝试链接一些数组和字符串方法,但它不起作用。如果有人能向我解释为什么这样的功能不起作用,那就太好了:

const scream = text => text.split('').push('!').join('').toUpperCase()

【问题讨论】:

  • 查看push 上的文档(它不会返回您推送到的数组,如果您查看抛出的错误应该很清楚)
  • 什么是示例文本以及预期内容
  • 这看起来是(text + '!').toUpperCase()的复杂版本

标签: javascript methods fluent chaining


【解决方案1】:

您可以使用Array#concat 来返回一个具有另一个值的数组,而不是Array#push,后者返回新的长度,但不是fluent interface 的一部分,以便稍后加入(需要一个数组)。

const scream = text => text.split('').concat('!').join('').toUpperCase();

console.log(scream('hi'));

【讨论】:

    【解决方案2】:

    Push 不返回数组。这是一个示例,演示了 push 发生了什么,并展示了另一种方法:

    const scream = text => text.split('').push('!').join('').toUpperCase()
    
    const test = ['a', 'b', 'c'];
    const result = test.push('!')
    
    console.log(result)
    
    const newScream = text => [
      ...text,
      '!'
    ].join('').toUpperCase()
    
    newScream('hello')
    
    console.log(newScream('hello'))

    【讨论】:

      【解决方案3】:

      如果要在末尾添加 1 个!

      const scream = text => text.split('').concat('!').join('').toUpperCase();
      

      如果你想在每个字母后面加上:

      const scream = text => text.split('').map(e => e + '!').join('').toUpperCase();
      

      push 不返回数组,因此在您的情况下不会在数组上调用 join

      【讨论】:

        【解决方案4】:

        如果您想在字符串末尾添加字符/字符串,请使用concat(<ch>) 函数。如果要将大小写更改为upper,请使用toUpperCase() 函数。

        或者

        您只需使用+ 运算符连接两个字符串并将! 附加到它。

        var str = "Hello World";
            var res = str.toUpperCase().concat("!");
            var result = (str + '!').toUpperCase();
            console.log(res);
            console.log(result);

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-05-05
          • 2013-02-04
          • 1970-01-01
          • 1970-01-01
          • 2023-03-31
          • 1970-01-01
          • 2013-06-20
          相关资源
          最近更新 更多