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

Chaining array and string methods in javascript

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

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

Push 不会 return 数组。下面是一个演示推送过程的示例,并展示了另一种方法:

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'))

您可以使用 Array#concat to return an array with another value instead of Array#push, which returns the new length, but is not part of a fluent interface 进行稍后的连接(这需要一个数组)。

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

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

如果要在末尾加1!:

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

如果要在每个字母后加上:

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

push 不使用 return 数组,因此在您的情况下 join 不会在数组上调用。

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

您可以简单地使用 + 运算符连接两个字符串并向其附加 !

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