Using iterable
built-in forEach
methods
var a = [‘A‘, ‘B‘, ‘C‘];a.forEach(function (element, index, array) { // element: 指向当前元素的值 // index: 指向当前索引 // array: 指向Array对象本身 alert(element);});
Set
Array
similar but Set
no index, so the first two parameters of the callback function are the elements themselves:
var s = new Set([‘A‘, ‘B‘, ‘C‘]);s.forEach(function (element, sameElement, set) { alert(element);});
Map
The callback function parameters are sequentially value
, key
and map
themselves:
var m = new Map([[1, ‘x‘], [2, ‘y‘], [3, ‘z‘]]);m.forEach(function (value, key, map) { alert(value);});
JS in the parameters do not require consistency, you can need a few write a few (of course, more than write is undefined, and parameter names can casually write "funny")
A.foreach (function (element, index, ARRAY,ADSF) {
Element: A value that points to the current element
Index: point to Current index
Array: points to the array object itself
Console.log (element, index, ARRAY,ADSF);
});
Vm2066:5 a 0 ["a", "B", "C"] undefined
Vm2066:5 B 1 ["A", "B", "C"] undefined
Vm2066:5 C 2 ["A", "B", "C"] undefined
For loop: Similar to foreach in Java:
for (var x of a) { alert(x); // ‘A‘, ‘B‘, ‘C‘}
The default object representation of JS is {} Key-value pairs, but the keys are all strings, so the map is referenced
var m = new Map ([[' Micheal ', 99],[' Bob ', 90],[' Baobao ', 100]]);
M.get (' micheal ');
You can also do this:
var m = new Map(); // 空Map m.set(‘Adam‘, 67); // 添加新的key-value m.set(‘Bob‘, 59); m.has(‘Adam‘); // 是否存在key ‘Adam‘: true m.get(‘Adam‘); // 67 m.delete(‘Adam‘); // 删除key ‘Adam‘ m.get(‘Adam‘); // undefined
Set is similar to list in Java but the values are not duplicated and the types are changeable;
The Add method adds an element,
Set([1, 2, 3, 3, ‘3‘]);
S.add (4); S.delete (2);
The map and set in JS