我尝试链接一些数组和字符串方法,但它不起作用。如果有人能向我解释为什么这样的函数不起作用,那就太好了:
const scream = text => text.split('').push('!').join('').toUpperCase()
你可以使用Array#concat
返回一个带有另一个值而不是Array#push
的数组,它返回新的长度,但不是fluent interface的一部分,用于以后的连接(需要一个数组)。
const scream = text => text.split('').concat('!').join('').toUpperCase();
console.log(scream('hi'));
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'))
如果你想在最后添加1个!
:
const scream = text => text.split('').concat('!').join('').toUpperCase();
如果你想在每个字母后添加它:
const scream = text => text.split('').map(e => e + '!').join('').toUpperCase();
push
不返回数组,因此在你的情况下不会在数组上调用join
。
如果要在字符串末尾添加字符/字符串,请使用concat(<ch>)
函数。如果你想将case更改为upper
,那么使用toUpperCase()
函数。
要么
只需你可以使用+
运算符连接两个字符串并追加!它。
var str = "Hello World";
var res = str.toUpperCase().concat("!");
var result = (str + '!').toUpperCase();
console.log(res);
console.log(result);