使用JavaScript中的for循环将数组的每个元素与特定字符连接起来
在这里,我们应该编写一个带有两个参数的函数,第一个参数是String或Number文字数组,第二个是String,我们必须返回一个字符串,其中包含该字符串在数组前后添加的所有元素。
例如-
applyText([1,2,3,4], ‘a’);
应该返回'a1a2a3a4a'
对于这些要求,与map()for循环相比,array方法是更好的选择,并且这样做的代码将是-
示例
const numbers = [1, 2, 3, 4];
const word = 'a';
const applyText = (arr, text) => {
const appliedString = arr.map(element => {
return `${text}${element}`;
}).join("");
return appliedString + text;
};
console.log(applyText(numbers, word));输出结果
此代码的控制台输出将是-
a1a2a3a4a