admin管理员组文章数量:1335386
I have an array. I want to add some characters (:,\n
) to each element in that array to be shown in a text box.
Currently this is what I'm doing
$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;
...
}
}
Is there a better way to do this?
I have an array. I want to add some characters (:,\n
) to each element in that array to be shown in a text box.
Currently this is what I'm doing
$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;
...
}
}
Is there a better way to do this?
Share Improve this question edited Jan 13, 2016 at 4:49 thefourtheye 240k53 gold badges465 silver badges500 bronze badges asked Jan 13, 2016 at 4:46 ThiyaguThiyagu 17.9k5 gold badges48 silver badges86 bronze badges 02 Answers
Reset to default 11You can simply use Array.prototype.map
to create a new Array object with the changed strings, like this
var textBox = {
text: $scope.source.arr.map(function(ele) {
return "***" + ele + " - ";
}).join("\n"),
...
};
For each element in the arr
, we are creating a new string corresponding to it and creating an array of strings. Finally we join all the strings in the array with \n
.
You can use Array.prototype.map, Array.prototype.reduce to make it better.
Check reduce function here https://developer.mozilla/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$$$
本文标签: javascriptHow to add some text to start and end of each element in an arrayStack Overflow
版权声明:本文标题:javascript - How to add some text to start and end of each element in an array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742389609a2465725.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论