how to map an array with uppercase function in javascript?

前端 未结 10 1286
野趣味
野趣味 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 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();
    });
    

提交回复
热议问题