在forEach循环中连接字符串



我正在尝试一些测试代码我把字符串转换成大写然后将它分割成一个数组,然后使用ES6 forEach循环遍历它然而,当我尝试将' hello '连接到循环的主题时它返回undefined

const string = 'abcd'
console.log(string.toUpperCase().split('').forEach(element => element += 'hello'))

当我给它加上join(")它会返回这个

undefined is not an object (evaluating string.toLowerCase().split('').forEach(element => element +=('hello')).join')

您需要使用map函数对数组元素进行任何更改

const string = 'abcd';
console.log(
string
.toUpperCase()
.split('')
.map(char =>
char += ' hello'
).join(', ')
);

map是正确的方法,但如果你需要使用forEach,使用它像这样:

const string = 'abcd'
var newstr = '';
string.toUpperCase().split('').forEach(element => newstr += element + 'hello');
console.log(newstr);

最新更新