Array方法总结 | 青训营笔记

109 阅读4分钟

循环----------

map(Value, Index, Array)

创建一个新数组,进行循环

//map直接接受参数
const account = 'John Evans';
console.log(
  account.toLowerCase().split(' ')
    /*.map(function (name, index, arr) {
      return name[0];
    })*/
    .map(name => name[0])
    .join('')
);       //je

filter()

创建一个新的数组,新数组中的元素是通过检查指定数组中 符合条件 的所有元素,主要用于符合条件的返回

const movent = [200, 450, -400, 3000, -650, -130, 70, 1300];
const withdrawals =
  // movent.filter(function (mov, index, arr) {
  //   return mov < 0;
  // });
  movent.filter(mov => mov < 0);
console.log(withdrawals);      //-400,-650,-130

reduce(callbackFn, initialValue)

initialValue : 初始值

主要用于统计计算,返回一个值

example 1: To accumulate total

const movent = [200, 450, -400, 3000, -650, -130, 70, 1300];
// acc == accumulator -> SNOWBALL
// second parameter is the initial value that need to accumulate
const reduce = movent.reduce(function (acc, mov, i, arr) {
  return acc + mov;
}, 0);
console.log(reduce);    //3840

example 2: To find the MAX value

const movent = [200, 450, -400, 3000, -650, -130, 70, 1300];
const max = movent.reduce((acc, mov) => {
  return acc > mov ? acc : mov;
}, movent[0]);
console.log(max);    //3000

Chain All Methods

链接式所有方法

const chain = movent
  .filter(mov => mov > 0)    //security
  .map(mov => mov * 2)    //singal data manipulataion
  .reduce((acc, mov) => acc + mov, 0);
console.log(chain);    //10040

filter()

创建新数组,返回所有符合条件的元素

find()

不创建数组,返回第一个匹配的元素

example 1 : 返回单元素

const movent = [200, 450, -400, 3000, -650, -130, 70, 1300];
const find = movent.find(mov => mov > 0);
const filter = movent.filter(mov => mov < 0);
console.log(find);		//200
console.log(filter);		//-400,-650,-130

example 2 : 返回对象

const userName = 'Tom';
const movent = [
  {
    username: 'Chris',
    age: 22,
  },
  {
    username: 'Tom',
    age: 20,
  },
];
let account = movent.find(acc => {
  console.log(acc.username);
  console.log(acc.username === userName);
  // if (acc.username === userName) return acc.username;
  // 条件通过,返回对象,find是顺序查找,返回的是index对应的对象
  return acc.username === userName;		//username: Tom, age: 20
});
console.log(account);

findIndex()

找到第一个匹配的索引并返回

const movent = [200, 450, -400, 3000, -130, 70, 1300];
const findIndex = movent.findIndex(mov => mov > 200);
console.log(findIndex);		//1

indexOf()

参数1: searchElement 参数2: fromIndex

const movent = [200, 450, -400, 3000, -130, 200, 70, 1300];
const indexOf = movent.indexOf(200);
const indexOf2 = movent.indexOf(200, 2);
console.log(indexOf);		//0
console.log(indexOf2);		//5

BOLLEAN返回类型----------

includes (searchElement, fromIndex)

fromIndex: 开始位置

平行测试,没有测试条件添加,被测试对象是否包含测试用例,返回 true / false

const movent = [200, 450, -400, 3000, -650, -130, 70, 1300];

console.log(movent.includes(mov => mov > 0));   //false
console.log(movent.includes(3000));   //true

some(callbackFn)

includes升级版,可添加条件判断

console.log(movent.some(mov => mov > 0));   //true
console.log(movent.some(mov => mov === 3000));    //true

every()

检测数组所有元素是否都符合指定条件 || 全符合: true || 只要有一个不符合: false

const movent = [200, 450, -400, 3000, -650, -130, 70, 1300];
console.log(movent.every(mov => mov > 0));		//false
console.log(movent.every(mov => typeof mov === 'number'));		//true

TIPS:

不对空数组进行检测 || 不会改变原始数组

在这里插入图片描述 LINK: every详情

元素拓展---------

flat (depth)

ES2019 引入,旧浏览器不适用

depth : 设置展开层次

默认展开一层数组

const movent = [200, 70, 1300, [3000, [-650, -130]]];
const flat = movent.flat(3);
const flat2 = movent.flat();
console.log(flat);
console.log(flat2);

在这里插入图片描述

faltMap (callbackFn, thisArg)

只能扩展一层无法改变(控制扩展层数)

const movent = [200, 70, 1300, [3000, [-650, -130]]];
const flatmap = movent
  .map(acc => acc)
  .flat(3)
  .reduce((acc, cur) => acc + cur, 0);
const flatmap2 = movent.flatMap(acc => acc).reduce((acc, cur) => acc + cur, 0);
console.log(flatmap);		//3790
console.log(flatmap2);		//4570, -650, -130

元素排序----------

sort()

基于字符串型排序

改变原数据

如果是数字,根据首位排序

const sort = [99, -100, 666, 333, -222];
const sortString = ['Chris', 'Tom', 'Mary'];

console.log(sort.sort());		//-100, -222, 333, 666, 99
console.log(`The original data:  ${sort.sort()}`);
console.log(sortString.sort());		//'Chris', 'Mary', 'Tom'
console.log(`The original data:  ${sortString.sort()}`);

数字正确排序

升序

//const sort = [99, -100, 666, 333, -222];
//way 2 :
const sortCorrectAscending = sort.sort((a, b) => {
  return a > b ? 1 : -1;
});
const sortCorrectAscending = sort.sort((a, b) => a - b);
console.log(sortCorrectAscending);		//-222, -100, 99, 333, 666

降序

//const sortCorrectDescending = sort.sort((a, b) => b - a);
//way 2 : 
const sortCorrectDescending = sort.sort((a, b) => {
  return a < b ? 1 : -1;
});
console.log(sortCorrectDescending);		//666, 333, 99, -100, -222

元素填充----------

常规数组创建

const arr = [1, 2, 3, 4, 5, 6];
const arrNew = new Array(1, 2, 3, 4, 5, 6);

fill (value, start, end)

value : 填充数值

start : 开始位置

end : 结束位置

改变原数组

const fillArr = new Array(6);
const fill = fillArr.fill(1);
// const matrix = new Array(6).fill().map(_ => new Array(6).fill(1));
const matrix = fillArr.map(_ => new Array(6).fill(1, 2, 5));
matrix[0][0] = 0;
console.log(`fillArr --- ${fillArr}`);
console.log(`fill --- ${fill}`);
console.log(matrix);

在这里插入图片描述

from (arrayLike, mapFn, thisArg)

arrayLike : 想要转换成数组的类数组或可迭代对象

mapFn 可选 : 调用数组每个元素的函数

  1. element : 当前的元素。

  2. index : 当前元素索引

thisArg 可选 : 执行 mapFn 时用作 this 的值

直接填充

const y = Array.from({ length: 7 }, () => 1);
console.log(y);		// 1 1 1 1 1 1 1

顺序填充 (_是占位符)

const z = Array.from({ length: 6 }, (_, i) => i + 1);
console.log(z);		//1 2 3 4 5 6

操作元素 :

使用 querySelectorAll , 产生NodeList (节点的集合,通常是由属性,如Node.childNodes 和 方法,如document.querySelectorAll 返回)

LINK : nodeList in MDN

<h1>Chris</h1>
<h1>Mary</h1>
<h1>999</h1>
btn.addEventListener("click", function () {
  const mov = Array.from(
    document.querySelectorAll("h1"),
    (el) => el.textContent
  );
  console.log(mov);

  const mov2 = [...document.querySelectorAll("h1")];
  //   console.log(mov2);
});

在这里插入图片描述

总结

在这里插入图片描述

?使用

const moventObj = {
  name: 'chris',
  age: {
    tom: 20,
    mary: 22,
  },
};
console.log(moventObj.sex.mary);		//ERROR
console.log(moventObj.sex?.mary);		//undefined
console.log(moventObj.age?.mary);		//22

在这里插入图片描述