JavaScript 数组方法学习总结

294 阅读3分钟

这是我的第一篇博客,一起参与掘金新人创作活动,开启写作之路。

在项目中时常用到数组的方法,但方法很多,又容易搞混,所以想将它们汇总到一起,便于查阅和对比。

方法汇总表

方法callback参数返回值说明
at--元素值与arr[index]一样
concat(value1[, value2[, ...[, valueN]]])新数组从数组后面拼接
copyWithin(target, start, end)改变后的数组本地操作
entries
every(element, index, array)true/false第一个不通过测试时结束
fill(value, start, end), start和end为空时覆盖所有元素改变后的数组改变原数组,value为引用类型时,所有填充的都同为value
filter(element, index, array)通过筛选的元素组成的新数组迭代所有元素
find(element, index, array)第一个查询到的元素
findIndex(element, index, array)第一个查询到的元素的索引
flat(depth), 参数为空时默认为1新数组扁平化数组
flatMap(element, index, array)新数组flat + map
forEach(cur, index, array)undefined对所有元素执行callback
from数组或类数组
includes(value, start)true/false===
indexOf(value, start)valueIndex/-1===
isArray
join(separator)字符串数组或类数组
keys
lastIndexOf(value, start)valueIndex/-1逆向查找
map(element, index, array)新数组对原数组每个元素调用callback,并返回新数组
of
pop数组最后一个元素出栈
push(value)新长度length入栈,数组和类数组
reduce(accumulator, currentElement, currentIndex, array), initialValue最终的accumulator是否指定初始值决定currentValue从0还是1开始. 用途:累加对象数组中包含的值
reduceRight👆👆是否指定初始值决定currentValue从-1还是-2开始
reverse顺序颠倒的数组
shift数组第一个元素删除数组第一个元素的数组
slice(start, end)截取的数组片段不包括end
some(element, index, array)true/false
sort(pre, next)排序后的数组
splice(start, deleteCount, replaceSequece)截取片段增删改数组
unshiftvalue新长度length增加第一个元素的数组
values

注意点

1. 不会跳跃稀疏数组的空元素(没有索引的元素)

  • map
  • for ... of ... 其他迭代方法都会跳过空元素

2. start值为负数,且小于-length时

仍然从0开始索引

3. end值大于等于length

索引从length开始

4. 从第一个元素调用callback开始,迭代范围就确定了

指的是索引序列确定。

  • arr=["1", "2", "3", "4", "5"] (以下称为数组),其索引序列范围为:0 -> 1 -> 2 -> 3 -> 4;
  • index为1时,执行(*),arr中的'1'会被删掉,此时的arr=["2", "3", "4", "5"](以下称为数组);
  • forEach不会随着原数组的长度变化而改变迭代范围,仍然会按照已经固定的索引序列范围(0 -> 1 -> 2 -> 3 -> 4)进行下去,也就是说以旧的索引序列范围遍历新数组
  • 程序已经执行过index=1了,接下来应该执行index=2,此时访问到的元素是新数组arr[2],即"4"
  • 可以看到,程序忽略了元素"3",因为index=1在执行(*)语句时就用过了,index=1下一个是index=2,就是上一步👆。

image.png

let arr = ["1", "2", "3", "4", "5"];
arr.forEach((ele, index) => {
  console.log(ele);
  if (index == 1) {
    arr.shift(); // '1'会被删除 (*)
  }
});

运行结果:

image.png

以上内容为自己的理解,仅用于自学记录。

参考: Array.prototype.forEach() - JavaScript | MDN (mozilla.org)