JavaScript -- 随笔 -- 数组

小声哔哔--看了第四版,记录一下自己喜欢的且常用的功能。

数组方法

.every() 与 .some()

传给两个个方法的函数都接收3个参数:数组元素、元素索引和数组本身。

.every() -- 对于每一项都需要返回true,它才会返回true

若中途有一项为false,则会退出循环

const arr = [1, 2, 3, 4, 5];
const everyRes = arr.every((item, i) => {
  console.log(i);  // 0 1 2
  return item < 3;
});
console.log(everyRes); // false
.some() -- 只要有一项返回true,它就会返回true

若中途有一项为true,则会退出循环

const arr = [1, 2, 3, 4, 5];
const someRes = arr.some((item, i) => {
  console.log(i);  // 0
  return item < 3;
});
console.log(someRes); // true
.filter() -- 返回为ture的组成新数组
const arr = [1, 2, 3, 4, 5];
const filterRes = arr.filter((item, i) => {
  return item > 3;
});
console.log(filterRes); // [4, 5]
.find() -- 返回数组中结果为true的第一个元素

若中途有一项为true,则会退出循环

const arr = [1, 2, 3, 4, 5];
const findRes = arr.find((item, i) => {
  return item > 3;
});
console.log(findRes); // 4

.map() 与 .forEach() 性能比较

既然比较了,顺便附上for;forin;forof的比较吧

const arr = new Array(99999);

console.time('map');
arr.map(item => 1);
console.timeEnd('map');
// map: 0.10791015625 ms

console.time('forEach');
arr.forEach(item => 1);
console.timeEnd('forEach');
// forEach: 0.0361328125 ms

console.time('forin');
for(let i in a) {}
console.timeEnd('forin');
// forin: 0.01513671875 ms

console.time('forof');
for(let i of a) {}
console.timeEnd('forof');
// forof: 0.587890625 ms

console.time('for');
for(let i =0 ; i < a; i++ ) {}
console.timeEnd('for');
// for: 0.0810546875 ms

执行了很多次,发现大部分情况速度排行是forin > forEach > for > map > forof
在chrome控制台执行,其他浏览器未实验。

.reduce() 与 reduceRight() --迭代数组的所有项,并在此基础上构建一个最终返回值

从第二项开始,prev为上一次return结果(初始为第一项)

const arr = [1, 2, 3, 4, 5];
const reduceRes = arr.reduce((prev, now, i, array) => {
  console.log(prev, now, i);  // 1 2 1; 3 3 2; 6 4 3; 10 5 4;
  return prev + now;
});
console.log(reduceRes); // 15
// reduceRight 从右到左 不重复贴了

2020-12-20 终止reduce

// 使用slice拷贝,浅拷贝自行修改
const reduceRes = arr.slice(0).reduce((prev, now, i, arr) => {
  console.log(i);  // 1; 2; 3;
  if(i > 2) arr.splice(1);
  return prev + now;
})
posted @ 2020-11-19 20:07  长长长长安  阅读(65)  评论(0)    收藏  举报