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

时间:2018-10-31 09:29:54

标签: javascript methods fluent chaining

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

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

4 个答案:

答案 0 :(得分:5)

您可以使用Array#concat返回具有另一个值而不是Array#push的数组,该数组返回新的长度,但不属于fluent interface的一部分,以便以后进行联接(需要数组)。

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

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

答案 1 :(得分:3)

推不返回数组。这是一个示例,演示了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'))

答案 2 :(得分:3)

如果要在末尾添加1个!

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

如果要在每个字母后添加它:

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

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

答案 3 :(得分:1)

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

只需使用+运算符即可合并两个字符串,并在其后附加

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

相关问题