笔记:《JavaScript学习指南》-第8章数组及其处理

第8章 数组及其处理
8.1 数组概览

8.2 操作数组内容
需要记住各个方法,是修改当前数组还是返回新数组。

8.2.1 在起始和末尾添加或删除元素
pop, push, shift, unshift

8.2.2 在末尾添加多个元素
concat(),添加多个元素并返回新数组的拷贝。

8.2.3 获取子数组
slice() ,第一个参数是起始位置,第二个参数是终止位置。
可用负数。

8.2.4 在任意位置添加或删除元素
splice()  。第一个参数是起始修改位置的数组位置;第二个是需要删除的个数;其他参数是需要添加到数组的元素。
const arr = [1,5,7];
arr.splice(1,0,2,3,4);    //返回[],arr现在是 [1, 2, 3, 4, 5, 7];
arr.splice(5,1,6);    //arr现在是 [1, 2, 3, 4, 5, 6]

8.2.5 数组内的分割和替换
ES6新方法.
coppyWithin() 它会将数组中一串有序的元素复制到数组的另一个位置,复制的同时会覆盖原来数组中的内容。
第一个参数表明要复制到哪里(目标位置),第二个参数是从哪里赋值,最后一个(可选的)参数是复制到哪里结束。
可用负数。

const arr = [1,2,3,4];

arr.copyWithin(1,2);    //arr现在是[1,3,4,4]
arr.copyWithin(2,0,2);    //arr现在是[1,3,1,3]
arr.copyWithin(0,-3,-1);    //arr现在是[3,1,1,3]

8.2.6 用指定值填充数组
ES6新方法。
fill() 将一个固定值赋给数组中任意位置元素(修改当前数组)。
可以任意指定一个起始下标位置和结束位置,然后填充这部分的数组值(下标可以为负值)。
const arr = new Array(5).fill(1);

arr.fill("a");    //arr现在是["a", "a", "a", "a", "a"]
arr.fill("b",1);    //arr现在是["a", "b", "b", "b", "b"]
arr.fill("c", 2, 4);    //arr现在是["a", "b", "c", "c", "b"]
arr.fill(5.5,-3);    //arr现在是["a", "b", 5.5, 5.5, 5.5]

8.2.7 数组反转和排序
reverse(), 颠倒当前数组的顺序。

sort() 对当前数组进行排序。

8.3 数组搜索
indexOf()
lastIndexOf()
查找到后返回下标,未找到返回-1

findIndex() 与indexOf() 一样,返回下标,可以指定一个函数来表示元素是否匹配。
findLastIndex()
const arr = [{ id: 5, name: "liang"}, {id:7, name: "zhu"}];

arr.findIndex(o => o.id === 5);    //0
arr.findIndex(0 => o.name === "zhu");    //1
arr.findIndex(o => o === 3);    //-1

find()  和findIndex() 都很适合查找特定元素的下标。运行指定一个函数来进行查找,返回元素本身而非元素下标。没找到时,返回null。
const arr = [{ id:5, name:"liang"}, {id:7, name:"zhu"}];

arr.find(o => o.id === 5);    //{id: 5, name: "liang"}

那些传入find 和findIndex 中的函数,会把数组的每一个元素作为第一个参数,其他参数还有当前元素 的下标和数组本身。
它们可以完成以下事情,比如:寻找以指定下标开始的元素的平方数。
const arr = [1, 17, 16, 5, 4, 15, 10, 3, 49];

arr.find((x,i) => i >2 && Number.isInteger(Math.sqrt(x)));    //4

find 和 findIndex 还允许在方法调用过程中指定 this 变量使用的值。
class Person{
    constructor(name){
        this.name = name;
        this.id = Person.nextId++;
    }
}

Person.nextId = 0;
const person1 = new Person("liang"),
      person2 = new Person("zhu"),
      person3 = new Person("lai");

const arr = [person1,person2,person3];

//选项1:直接比较id
arr.find(p => p.id === person2.id);    // Person {name: "zhu", id: 1}

//选项2:利用 this 参数
arr.find(p => p.id === this.id, person2);

some()  只要找到一个符合条件的元素,就会停止查找并返回true,否则返回false。
every()   数组中的每个元素都符合条件,才会返回true。只要发现一个不符合就会停止查找并返回false。
它们可以接受一个方法作为参数,还能再接收一个参数,用来指定方法被调用时的 this 值。

8.4 数组的基本操作:map 和 filter
map() 可以把元素转换成数组,数组类型由开发者决定。
const cart = [{name:"Widget", price: 32}, {name:"Gadget", price: 21}];

const names = cart.map(x => x.name);    //names的数组为 ["Widget", "Gadget"]
const price = cart.map( x => x.price);    //price的数组为[32, 21]

const discountPrice = cart.map( x => x.price*0.8);    //discountPrice的数组为[25.6, 16.8]
const lcNames = cart.map(x => x.name.toLowerCase());    //lcName的数组为["widget", "gadget"]

数组每个元素在调用提供的方法时都会传入三个参数:元素本身、元素下标,以及数组本身(这个不常用)。
const names = ["liang", "zhu"];
const ages = [26, 25];

const person = names.map((x,i) => ({name: x, age: ages[i]}));
person;    //[{name: "liang", age: 26},{name: "zhu", age: 25}]
map 使用了元素本身 x,还有它的索引 i。在花括号外添加一层小括号,避免对象被当成代码块。这里map通过从不同的数组中提取信息,从而把一个字符串类型的数组转化成了一个数组对象。

filter() 用来创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。

8.5 数组魔法:reduce
reduce() 经常被用于将一个数组归纳成一个单独的值。比如对数组进行求和或者计算平均值。
第一个参数是累加值,表示数组将被归纳成的值。剩下的参数为:当前数组元素、当前元素的下标和数组的。
给数组求和:
const arr = [5, 3, 6, 2];
const sum = arr.reduce((a,x) => a += x, 0);    //0为a的初始值,可以省略

将对象作为累加结果:
//将string类型的数组以首字母开头的属性进行分组,每个组作为一个数组元素
const words = ["Baa", "Roo", "Ang", "Annd", "Ngeee", "Khhn","Ehhj"];
const alphabetical = words.reduce((a,x) =>{
    if(!a[x[0]]) a[x[0]] = [];
    
    a[x[0]].push(x);
    
    return a;
},{});
对于数组中的每个元素,函数都会检查累加结果,来判断结果中是否包含元素的第一个字母。如果不包含,就创建一个空数组。然后它会把元素放在对应的数组中。最终,累加结果 a 会被返回。

将字符串作为累加结果:
const words = ["Hi", "Nihao", "Your", "Name", "Computer", "Internet", "Web", "You"];
const longWords = words.reduce((a,w) => w.length>5 ? a+" " +w : a, " ").trim();
//存放所有长度大于5个字母的字符串
// longWords的值为  "Computer Internet"

8.6 数组方法,已删除或者未定义的元素
 当数组中的元素未被赋值或已被删除时,map、filter 和 reduce 就不会调用所传入的函数。
如果从数组中删除一个元素,然后再调用 map,就会得到一个有“缺口”的数组:
const arr = [1,2,3,4,5];

delete arr[2];
arr.map(x => 0);    // [0, 0, empty, 0, 0]
这种情况很罕见,一般情况不会在数组中用 delete。

8.7 字符串连接
join() 接受一个分隔符作为参数,返回一个连接了所有元素的字符串。
const arr = [1, null, "hello", "world", true, undefined];

delete arr[3];
arr.join();    // "1,,hello,,true,"
arr.join(' ');    // "1  hello  true "

可用来创建HTML中<ul>的列表:
const attributes = ["liang", "zhu", "lin"];
const html = "<ul><li>" + attributes.join("</li><li>") + "</li></ul>";

猜你喜欢

转载自blog.csdn.net/kjhz_liang/article/details/80531313
今日推荐