在javascript中链接数组和字符串方法

问题描述 投票:2回答:4

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

const scream = text => text.split('').push('!').join('').toUpperCase()
javascript methods fluent chaining
4个回答
5
投票

你可以使用Array#concat返回一个带有另一个值而不是Array#push的数组,它返回新的长度,但不是fluent interface的一部分,用于以后的连接(需要一个数组)。

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

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

3
投票

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


1
投票

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

要么

只需你可以使用+运算符连接两个字符串并追加!它。

var str = "Hello World";
    var res = str.toUpperCase().concat("!");
    var result = (str + '!').toUpperCase();
    console.log(res);
    console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.