how to map an array with uppercase function in javascript?

前端 未结 10 1267
野趣味
野趣味 2021-02-12 19:29

I\'m interested if there is any function like array_map or array_walk from php.

Don\'t need an for that travels all the array. I can do that for myself.



        
相关标签:
10条回答
  • 2021-02-12 19:59

    You could consider using the Underscore.js library which provides standard functional operations.

    Then the code would be as simple as:

    _.map(array, function (x) { return x.toUpperCase(); });
    
    0 讨论(0)
  • 2021-02-12 20:01

    I understand it is a little late to the party, but I wanted to add this here as another Delegation way of doing it.

    var array = ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'];
    
    "".toUpperCase.apply(array).split(',')
    
    0 讨论(0)
  • 2021-02-12 20:02

    map() is somehow similar to array_walk

    http://jqapi.com/#p=map

    0 讨论(0)
  • 2021-02-12 20:02

    You can use $.map() in order to apply String.toUpperCase() (or String.toLocaleUpperCase(), if appropriate) to your array items:

    var upperCasedArray = $.map(array, String.toUpperCase);
    

    Note that $.map() builds a new array. If you want to modify your existing array in-place, you can use $.each() with an anonymous function:

    $.each(array, function(index, item) {
        array[index] = item.toUpperCase();
    });
    

    Update: As afanasy rightfully points out in the comments below, mapping String.toUpperCase directly will only work in Gecko-based browsers.

    To support the other browsers, you can provide your own function:

    var upperCasedArray = $.map(array, function(item, index) {
        return item.toUpperCase();
    });
    
    0 讨论(0)
  • 2021-02-12 20:04

    You can implement a function for it:

    Array.prototype.myUcase=function()
    {
      for (i=0;i<this.length;i++)
        {
        this[i]=this[i].toUpperCase();
        }
    }
    

    USAGE

    var fruits=["Banana","Orange","Apple","Mango"];
    fruits.myUcase();
    

    RESULT

    BANANA,ORANGE,APPLE,MANGO 
    

    Reference LINK

    0 讨论(0)
  • 2021-02-12 20:07

    Check out JavaScript Array.map for info on the official JavaScript map function. You can play around with the sample there to see how the function works. Try copying this into the example box:

    var array = ['dom', 'lun', 'mar', 'mer', 'gio', 'ven', 'sab'];
    var uppers = array.map(function(x) { return x.toUpperCase(); });
    console.log(uppers);
    

    And it will print:

    DOM,LUN,MAR,MER,GIO,VEN,SAB
    
    0 讨论(0)
提交回复
热议问题