javascript 如何为数组值添加前缀?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26115971/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to add prefix to array values?
提问by Navin Rauniyar
I've array values to which I want to add some prefix:
我有要添加一些前缀的数组值:
var arr = ["1.jpg","2.jpg","some.jpg"];
Adding prefix images/
should result this:
添加前缀images/
应该会导致:
newArr = ["images/1.jpg","images/2.jpg","images/some.jpg"];
回答by Roman Kolpak
Array.prototype.map
is a great tool for this kind of things:
Array.prototype.map
是处理此类事情的绝佳工具:
arr.map(function(el) {
return 'images/' + el;
})
In ES2015+:
在 ES2015+ 中:
arr.map(el => 'images/' + el)
回答by Todd Mark
回答by alex
For browser compatibility and without loop:
对于浏览器兼容性和无循环:
var pre = 'images/';
var arr = ['1.jpg', '2.jpg', 'some.jpg'];
var newArr = (pre + arr.join(';' + pre)).split(';');
回答by Johnroe Paulo Ca?amaque
You can simply do this with a simple loop:
你可以用一个简单的循环简单地做到这一点:
var arr = ["1.jpg","2.jpg","some.jpg"],
newArr = [];
for(var i = 0; i<arr.length; i++){
newArr[i] = 'images/' + arr[i];
}
回答by kemenov
You can use Jquery library
您可以使用 Jquery 库
var newArr = jQuery.map( arr, function( n, i ) {
return ( "images/"+n );
});