How to add prefix to array values?

前端 未结 5 1712
遇见更好的自我
遇见更好的自我 2020-12-01 10:40

I have an array of values to which I want to add some prefix:

var arr = ["1.jpg", "2.jpg", "some.jpg"];

Adding

相关标签:
5条回答
  • 2020-12-01 11:03

    You can use Jquery library

    var newArr = jQuery.map( arr, function( n, i ) {
      return ( "images/"+n );
    });
    
    0 讨论(0)
  • 2020-12-01 11:11

    Array.prototype.map is a great tool for this kind of things:

    arr.map(function(el) { 
      return 'images/' + el; 
    })
    

    In ES2015+:

    arr.map(el => 'images/' + el)
    
    0 讨论(0)
  • 2020-12-01 11:14

    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];
    }
    
    0 讨论(0)
  • 2020-12-01 11:22

    For browser compatibility and without loop:

    var pre = 'images/';
    var arr = ['1.jpg', '2.jpg', 'some.jpg'];
    var newArr = (pre + arr.join(';' + pre)).split(';');
    
    0 讨论(0)
  • 2020-12-01 11:26

    Use Array.prototype.map():

    const newArr = arr.map(i => 'images/' + i)
    

    Same thing but without using ES6 syntax:

    var arr = arr.map(function (i){
        return 'images/' + i;
    })
    
    0 讨论(0)
提交回复
热议问题