简体   繁体   中英

Append to each element in an array in Javascript

With an array, how would I append a character to each element in the array? I want to add the string ":" after each element and then print the result.

 var a = [54375, 54376, 54377, 54378, 54379, 54380, 54381, 54382, 54383, 54384, 54385, 54386, 54387, 54388, 54389, 54390, 54391, 54392, 54393, 54394, 54395, 54396, 54397, 54400, 54402, 54403, 54405, 54407, 54408];

For example: 54375:54376:54377

a = a.map(function(el) { return el + ':'; });

或者,如果你想加入他们为一个字符串:

var joined = a.join(':');

If you are looking for a way to concatenate all the elements with : , you can use this

var result = "";
for (var i = 0; i < a.length; i += 1) {
    result += a[i] + ":";
}
result = result.substr(0, result.length-1);

Or even simpler, you can do

a = a.join(":");

If you are looking for a way to append : to every element , you can use Array.prototype.map , like this

a = a.map(function (currentItem) {
    return currentItem + ":";
});
console.log(a);

If your environment doesn't support map yet, then you can do this

for (var i = 0; i < a.length; i += 1) {
    a[i] = a[i] + ":";
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM