-
forEach(callback(element, index, array)) : 遍历数组并对每个元素执行回调函数。
const array = [1, 2, 3]; array.forEach((element, index) => { console.log(`Index ${index}: ${element}`); }); -
map(callback(element, index, array)) : 创建一个新数组,其元素是原数组经过回调函数处理后的结果。
const array = [1, 2, 3]; const squaredArray = array.map((element) => element ** 2); -
filter(callback(element, index, array)) : 创建一个新数组,其中包含原数组中满足条件的元素。
const array = [1, 2, 3, 4, 5]; const evenNumbers = array.filter((element) => element % 2 === 0); -
reduce(callback(accumulator, element, index, array), initialValue) : 对数组中的所有元素执行一个累加器函数,返回一个累积的结果。
const array = [1, 2, 3, 4]; const sum = array.reduce((accumulator, element) => accumulator + element, 0); -
find(callback(element, index, array)) : 返回数组中满足条件的第一个元素,如果没有找到则返回 undefined。
const array = [1, 2, 3, 4, 5]; const foundElement = array.find((element) => element > 2); -
indexOf(element, startIndex) : 返回数组中指定元素的第一个匹配项的索引,如果未找到则返回 -1。
const array = [1, 2, 3, 4, 5]; const index = array.indexOf(3); -
push(element1, element2, ...) : 向数组末尾添加一个或多个元素,并返回新数组的长度。
javascriptCopy codeconst array = [1, 2, 3]; const newLength = array.push(4, 5); -
pop() : 移除数组末尾的元素,并返回被移除的元素。
const array = [1, 2, 3]; const removedElement = array.pop(); -
shift() : 移除数组头部的元素,并返回被移除的元素。
const array = [1, 2, 3]; const removedElement = array.shift(); -
unshift(element1, element2, ...) : 在数组头部添加一个或多个元素,并返回新数组的长度。
const array = [2, 3, 4]; const newLength = array.unshift(1);