如何使用map在每个数组元素的末尾添加文本? [英] How to add text to end of each array element using map?
本文介绍了如何使用map在每个数组元素的末尾添加文本?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个映射到数组的函数,并将一串文本添加到数组中每个元素的末尾。当我执行console.log时,我只会得到 undefined
。任何帮助将不胜感激。
I am trying to write a function that maps over an array and add a string of text to the end of each element in the array. When I do a console.log I just get undefined
. Any help would be greatly appreciated.
这里是数组:
let arr = ["England","Scotland","Westeros"];
这就是我要尝试的:
dragonMapper = (arr) => {
let newArr = arr.map(function(e) {
e += '...here be dragons'
});
return newArr;
}
console.log(dragonMapper(newArr));
这是我希望函数执行后的数组:
This is what I want the array to be after the function is executed:
["England...here be dragons","Scotland...here be dragons","Westeros...here be dragons"];
推荐答案
.map
的回调函数期望返回值
.map
's callback function expects a return value
let arr = ["England", "Scotland", "Westeros"];
dragonMapper = arr => {
let newArr = arr.map(function(e) {
return e + '...here be dragons'; //Return the concatenated value of 2 strings
});
return newArr;
}
console.log(dragonMapper(arr));
更短版本,带有箭头函数语法:
Shorter version, with the arrow function syntax:
let arr = ["England", "Scotland", "Westeros"];
dragonMapper = arr => {
return arr.map(e => e + '...here be dragons');
}
console.log(dragonMapper(arr));
这篇关于如何使用map在每个数组元素的末尾添加文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文