array functions

5503 ワード

map

const array = [1, 2, 3];
const doubled = array.map((num) => {
  return num * 2;
});
                          

indexOf


find out and return the position of the first occurrence of a value in an array.
const alphabet = ['a', 'b','c'];
const index = alphabet.indexOf('b');
console.log(index);// 1
                          

filter


create an array made of elements that pass a test provided by a function
const words = ['tomato', 'egg', 'onion', 'garlic', 'pepper'];
const result= words.filter(word => word.length > 5);
console.log(result);// ['tomato', 'garlic', 'pepper']

find


return the first element of an array that pass a test provided by a function, if not, return 'undefined'
const words = ['tomato', 'egg', 'onion', 'garlic', 'pepper'];
const result= words.find(word => word.length < 5);
console.log(result);// egg