如何在数组的每个元素开头和结尾添加一些文本

3

我有一个数组。我想要在每个元素中添加一些字符 (:,\n),以便在文本框中显示。

目前我的做法是:

$scope.source.arr = .... //This is an array
var actualText = "";

function func() {
    $scope.source.arr.forEach(function(ele){
        actualText += "***" + ele + " - \n"; //Adding necessary characters
    })
}

var showText = function() {
    func(); //Calling the function that populates the text as needed
    var textBox = {
          text : actualText; 
          ...
     }
}

有更好的方法来实现这个吗?

2个回答

11

您可以简单地使用Array.prototype.map来创建一个带有更改字符串的新数组对象,代码如下

var textBox = {
      text: $scope.source.arr.map(function(ele) {
          return "***" + ele + " -  ";
      }).join("\n"),
      ...
 };
对于arr中的每个元素,我们都创建一个相应的新字符串并创建一个字符串数组。最后,我们使用\n将数组中的所有字符串连接起来。

所以如果我的理解是正确的,该函数不会为每个元素返回字符串,而是为整个数组返回字符串数组(字符串表示形式)。我是对的吗? - Thiyagu
@user7 map函数传递的函数将被调用数组中的所有项目,并收集从函数调用返回的所有值,并作为一个数组返回。该数组将与join函数连接以获得单个字符串。 - thefourtheye

1
你可以使用 Array.prototype.map 和 Array.prototype.reduce 使其更好。
在这里检查 reduce 函数 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce
var prefix = "***";
var postfix = "$$$";

var targetStrArr = ["apple", "banana"]

var resultStr = targetStrArr.map(function(ele){
    return prefix + ele + postfix; //Adding necessary characters
}).reduce(function(prevVal, curVal) {
    return prevVal + curVal;
});

console.log(resultStr); // ***apple$$$***banana$$$

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接