forEach Method (Map) (JavaScript)

Performs the specified action for each element in a map.

mapObj.forEach(callbackfn[, thisArg])

mapObj

Required. A Map object.

callbackfn

Required. The function that forEach calls one time for each element in the map. callbackfn accepts up to three arguments. forEach calls the callbackfn function one time for each element in the map.

thisArg

Optional. An object that the this keyword can refer to in the callbackfn function. If thisArg is omitted, undefined is used as the this value.

If the callbackfn argument is not a function object, a TypeError exception is thrown.

The syntax of the callback function is as follows:

function callbackfn(value, key, mapObj)

You can declare the callback function by using up to three parameters, as shown in the following table.

Callback argument

Definition

value

A value contained in the map.

key

A key contained in the map.

mapObj

The Map object to traverse.

The following example shows how to retrieve members of a Map using forEach.

var m = new Map();
m.set(1, "black");
m.set(2, "red");
m.set("colors", 2);
m.set({x:1}, 3);

m.forEach(function (item, key, mapObj) {
    document.write(item.toString() + "<br />");
});

document.write("<br />");
document.write(m.get(2));

// Output:
// black
// red
// 2
// 3
//
// red

Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). See Version Information. Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards. Not supported in Windows 8.

Show:
© 2014 Microsoft