2016-01-13 42 views
2

我有一個數組。我想爲該數組中的每個元素添加一些字符(:,\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; 
      ... 
    } 
} 

有沒有更好的方式來做到這一點?

回答

9

您可以簡單地使用Array.prototype.map創造與改變的字符串的新Array對象,這樣

var textBox = { 
     text: $scope.source.arr.map(function(ele) { 
      return "***" + ele + " - "; 
     }).join("\n"), 
     ... 
}; 

對於每一個元素在arr,我們正在創建對應於一個新的字符串,並創建數組字符串。最後我們加入\n這個數組中的所有字符串。

+0

大.. !!!那麼這個'return'在這裏表現如何?它會返回一個數組嗎? – user7

+0

因此,如果我的理解是否正確,函數將不會爲每個元素返回字符串,而是返回整個數組的字符串(字符串表示形式)數組。我對嗎? – user7

+0

@ user7傳遞給map的函數將針對數組中的所有項目調用,並且函數調用返回的所有值將作爲數組收集並返回。該數組將與'join'函數結合以獲得單個字符串。 – thefourtheye

0

您可以使用Array.prototype.map,Array.prototype.reduce使其更好。

檢查減少此功能https://developer.mozilla.org/en-US/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$$$ 
相關問題