附加到 JavaScript 参数中的所有值

appending to all values in a javascript arrary

本文关键字:参数 JavaScript      更新时间:2023-09-26

假设我有一个这样的字符串数组:

originalArray = ["some value", "another value", "and another"]

您将如何添加到每个字符串的开头和结尾,使其看起来像这样:

finalArray = ["FIRST some value LAST", "FIRST another value LAST", "FIRST and another LAST"]

(显然我可以使用循环,但我认为有一种更有效的方法)

使用 Array.prototype.map()

map() 方法创建一个新数组,其中包含在此数组中的每个元素上调用提供的函数的结果。(来源)

例如

var originalArray = ["some value", "another value", "and another"];
var fixedArray = originalArray.map(function(item){
        return "FIRST " + item + " LAST";
    });

结果

["FIRST some value LAST", "FIRST another value LAST", "FIRST and another LAST"]