Adding text to beginning of each array element

前端 未结 7 1393
[愿得一人]
[愿得一人] 2020-11-30 06:49

I have an array which contains the contents as follows:

[\"ZS125-48ATab\", \"STR125YBTab\", \"KS125-24Tab\", \"ZS125-50Tab\", \"DFE125-8ATab\", \"ZS125-30Tab         


        
相关标签:
7条回答
  • 2020-11-30 07:00

    Iterate over the array and just add #

    var arr = [your array];
    
    for (var i=arr.length; i--;) {
        arr[i] = '#' + arr[i];
    }
    

    FIDDLE

    In newer browsers you could do

    arr = arr.map(function(e) {return '#' + e});
    
    0 讨论(0)
  • 2020-11-30 07:03

    Example for ES6

    var arr = ['first', 'second', 'third'];    
    arr = arr.map(i => '#' + i);
    

    Result:

    console.log(arr); // ["#first", "#second", "#third"]
    
    0 讨论(0)
  • 2020-11-30 07:04

    You can do it like this :

    array = ('#' + array.join('#')).match(/#[^#]*/g) || []; // null || []
    

    The following trick works as well, but I wonder why split ignores the first sharp...

    array = ('#' + array.join('#')).split(/(?=#)/);
    

    Indeed, I rather expected this scenario : "#a#b#c" -> ["", "#a", "#b", "#c"].

    Anyway, I prefer the second method since match returns null in case of failure.

    0 讨论(0)
  • 2020-11-30 07:06

    Simple & sweet in ES6 as,

    array.map((line) => `#${line}`);
    
    0 讨论(0)
  • 2020-11-30 07:15
    for(var i=0;i<array.length;i++){
        array[i]="#"+array[i];
    }
    
    0 讨论(0)
  • 2020-11-30 07:16

    Use the forEach method(reference)

    var array = ["ZS125-48ATab", "STR125YBTab", "KS125-24Tab", "ZS125-50Tab", "DFE125-8ATab", "ZS125-30Tab", "HT125-8Tab", "HT125-4FTab", "STR50Tab"];
    array.forEach(function(element, index) {
        array[index] = '#' + element;
    });
    
    0 讨论(0)
提交回复
热议问题