简体   繁体   English

Javascript快捷方式,将字符串附加到数组的所有值中?

[英]Javascript shortcut, to append string into all the values of array?

I have an array = ["a", "b", "c"]; 我有一个array = ["a", "b", "c"];

What I want is i have an string let us say "Hello", that I want to append to each and every value of this array. 我想要的是我有一个字符串让我们说“ Hello”,我想将其附加到此数组的每个值上。

My expected output is something like 我的预期输出是这样的

["Hello_a", "Hello_b", "Hello_c"]

Is there any shortcut in javascript to perform this operation, without using any loop . javascript中是否有任何快捷方式可以执行此操作,而无需使用任何循环。

Any help is appreciated ! 任何帮助表示赞赏!

Thanks 谢谢

Try to use Array.prototype.map() at this context, 尝试在这种情况下使用Array.prototype.map()

var yourArray = ["a", "b", "c"];
var transformed = yourArray.map(function(item){
  return "Hello_" + item;
});
console.log(transformed); // ["Hello_a", "Hello_b", "Hello_c"]

Also you can use fat Arrow functions if users of you are updated with latest browsers. 如果您的用户已使用最新的浏览器更新,则还可以使用胖箭头功能。

var yourArray = ["a", "b", "c"];
var transformed = yourArray.map(item => "Hello_" + item);
console.log(transformed); // ["Hello_a", "Hello_b", "Hello_c"]

As a side note, you have to sure about arrow functions that it will forcibly use lexical this inside of it. 作为附带说明,您必须确定箭头函数会强制在其内部使用lexical this

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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