arr.forEach(function(item, index, array) {// ... do something with item});// for each element call alert["Bilbo","Gandalf","Nazgul"].forEach(alert);["Bilbo","Gandalf","Nazgul"].forEach((item, index, array) => {alert(`${item} is at index ${index} in ${array}`);});
Searching in array
indexOf/lastIndexOf and includes
arr.indexOf(item, from) looks for item starting from index from, and returns the index where it was found, otherwise -1.
arr.lastIndexOf(item, from) – same, but looks for from right to left.
arr.includes(item, from) – looks for item starting from index from, returns true if found.
let arr = [1,0,false];alert( arr.indexOf(0) ); // 1alert( arr.indexOf(false) ); // 2alert( arr.indexOf(null) ); // -1alert( arr.includes(1) ); // true// use ===constarr= [NaN];alert( arr.indexOf(NaN) ); // -1 (should be 0, but === equality doesn't work for NaN)alert( arr.includes(NaN) );// true (correct)
find and findIndex 若 array 的元素是物件,要找到特定物件用 find,只返回第一個符合函示元素。
item is the element.
index is its index.
array is the array itself.
let result =arr.find(function(item, index, array) {// if true is returned, item is returned and iteration is stopped// for falsy scenario returns undefined});let users = [ {id:1, name:"John"}, {id:2, name:"Pete"}, {id:3, name:"Mary"}];let user =users.find(item =>item.id ==1);alert(user.name); // John
filter 跟 find 很像,但會返回所有符合函式的元素。
let results =arr.filter(function(item, index, array) {// if true item is pushed to results and iteration continues// returns empty array for complete falsy scenario});let users = [ {id:1, name:"John"}, {id:2, name:"Pete"}, {id:3, name:"Mary"}];// returns array of the first two userslet someUsers =users.filter(item =>item.id <3);alert(someUsers.length); // 2
Transform an array
map 將 array 每個元素帶入函式並返回新的 array
let result =arr.map(function(item, index, array) {// returns the new value instead of item})let lengths = ["Bilbo","Gandalf","Nazgul"].map(item =>item.length);alert(lengths); // 5,7,6
sort(fn)
// sort 依照 string 排序let arr = [ 1,2,15 ];// the method reorders the content of arr (and returns it)arr.sort();alert( arr ); // 1, 15, 2// 要用自定義的函式當參數functioncompareNumeric(a, b) {if (a > b) return1;if (a == b) return0;if (a < b) return-1;}let arr = [ 1,2,15 ];arr.sort(compareNumeric);alert(arr); // 1, 2, 15// 比較函式返回正數代表較大,返回負數代表較小let arr = [ 1,2,15 ];arr.sort(function(a, b) { return a - b; });alert(arr); // 1, 2, 15// 更短的寫法arr.sort( (a, b) => a - b );
reverse
let arr = [1,2,3,4,5];arr.reverse();alert( arr ); // 5,4,3,2,1
// str.split()let names ='Bilbo, Gandalf, Nazgul';let arr =names.split(', ');for (let name of arr) {alert( `A message to ${name}.` ); // A message to Bilbo (and other names)}// 第 2 個參數指定返回 array 的長度let arr ='Bilbo, Gandalf, Nazgul, Saruman'.split(', ',2);alert(arr); // Bilbo, Gandalf// 空字串返回字母組成的 arraylet str ="test";alert( str.split('') ); // t,e,s,t// arr.join()let arr = ['Bilbo','Gandalf','Nazgul'];let str =arr.join(';');alert( str ); // Bilbo;Gandalf;Nazgul
reduce/reduceRight
previousValue – is the result of the previous function call, initial for the first call.
item – is the current array item.
index – is its position.
array – is the array.
let value =arr.reduce(function(previousValue, item, index, array) {// ...}, initial);let arr = [1,2,3,4,5];let result =arr.reduce((sum, current) => sum + current,0);alert(result); // 15
// samelet arr = [1,2,3,4,5];// removed initial value from reduce (no 0)let result =arr.reduce((sum, current) => sum + current);alert( result ); // 15// error if array is empty so suggest to set intial value let arr = [];// Error: Reduce of empty array with no initial value// if the initial value existed, reduce would return it for the empty arr.arr.reduce((sum, current) => sum + current);