Javascript map native object methods

In Python, you can something like this:

>>> list(map(str.upper, ['foo','bar']))
['FOO', 'BAR']

I would like to be able to do something like this in javascript:

I tried the following in Chrome using the built-in map implementation ( https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/map ):

['foo','bar'].map(String.prototype.toUpperCase)

['foo','bar'].map(String.prototype.toUpperCase.call)

Why don't you call a job? Is there any elegant way to do this or should I wrap toUpperCase in a callback function? thank

+3
source share
5 answers

Modern browsers support this ( although this is the latest addition )

var a = ['foo','bar'];
var b = a.map(String.toUpperCase);

alert(b[1]);

or even

var a = ['foo','bar'].map(String.toUpperCase);
alert(a[0]);

example: http://www.jsfiddle.net/xPsba/

+1

Try:

['foo','bar'].map(Function.prototype.call.bind(String.prototype.toUpperCase))

:

['foo','bar'].map(Function.call.bind("".toUpperCase))

JavaScript this - .

+2

, String.prototype.toUpperCase this (Context), map . .

['foo','bar'].map(function(k) { return String.prototype.toUpperCase.call(k) });
+1

.: -)

( ) . map:

a.map(function(x){x.frob()})

. :

a.mapm(A.frob)

A - A, mapm - Array, this ( A ). mapm :

Array.prototype.mapm = function (method)
{
    return this.map(function (x) { return method.apply(x) } )
};

:

["a", "b", "c"].mapm("".toUpperCase)    ==>     ["A", "B", "C"]

The only problem is that you added a new element mapmto each array, although it is ignored by most methods Array, for example. lengthand map.

+1
source

You can use something like this:

function map(arr, fn){
    var i = 0, len = arr.length, ret = [];
    while(i < len){
        ret[i] = fn(arr[i++]);
    }
    return ret;
}

And use it:

var result = map(['foo', 'bar'], function(item) {
    return item.toUpperCase();
});

console.log ( result ); // => ['FOO', 'BAR']
-1
source

Source: https://habr.com/ru/post/1774583/


All Articles