JavaScript系列:浅析Array

前言

本文是结合JavaScript30,对Array的回顾与总结,主要结合问题总结一些API的用法。部分语法使用的ES6的书写规范。
首先说明JavaScript中的数组(Array)是引用类型,可以包含任意的数据类型,并通过索引来访问每一个元素。

遍历

for循环 &for/in &for/of

    
    var a = [4,5,6,8,7]
    a.foo = "hello"
    //for循环
    for(var i = 0; i<a.length; i++){
        console.log(a[i])  // logs 4 5 6 8 7  
    }
    // for/in
    for(var index in a){
        console.log(a[index])   // logs 4 5 6 8 7 hello
    }
    // for/of
    for(var value of a){
        console.log(value)  // logs 4 5 6 8 7
    } 

看上去for循环和for/of的结果一样,但是for循环只是简单的循环语句,而for/of语句是在可迭代对象上创建一个迭代循环,当然数组也属于可迭代对象的一种。
for循环:循环条件是< a.length,让数组具有了对象属性,此时的a.length依旧是5,所以不会循环到a.foo的值。
for/of:属于ES6的语法,并不是适用于所有的Object。它会迭代(循环)出该对象中拥有Symbol.iterator属性的元素,具有这样属性的元素可枚举性为false
for/in:其实一直都是使用来循环Object(对象)的,因为数组也是对象,所以可是使用,可如果是通常的数组元素遍历是升序的,当不能保证一定一这样(主要是因为对象是无序的)。该循环会遍历一个Object所有可枚举(遍历)的属性。

数组方法

join()

将数组所有元素拼接为字符串,返回最后的字符串。

    // 在没有ES6的模版字符串的时候 可以讲生成的DOM节点放在数组中最后使用join方法拼接出来
    const html = ["<ul>","<li>hello</li>","<li>world</li>","</ul>"].join("");
    document.body.appendChild(html)

reverse()

将数组元素颠倒

    const a = [1,2,3]
    a.reverse().join("")  // 321

sort()

将数组排序并返回排序后的数组改变原数组

    const people = ['Beck, Glenn', 'Becker, Carl', 'Beckett, Samuel', 'Beddoes, Mick', 'Beecher, Henry', 'Beethoven, Ludwig', 'Begin, Menachem', 'Belloc, Hilaire', 'Bellow, Saul', 'Benchley, Robert', 'Benenson, Peter', 'Ben-Gurion, David', 'Benjamin, Walter', 'Benn, Tony', 'Bennington, Chester', 'Benson, Leana', 'Bent, Silas', 'Bentsen, Lloyd', 'Berger, Ric', 'Bergman, Ingmar', 'Berio, Luciano', 'Berle, Milton', 'Berlin, Irving', 'Berne, Eric', 'Bernhard, Sandra', 'Berra, Yogi', 'Berry, Halle', 'Berry, Wendell', 'Bethea, Erin', 'Bevan, Aneurin', 'Bevel, Ken', 'Biden, Joseph', 'Bierce, Ambrose', 'Biko, Steve', 'Billings, Josh', 'Biondo, Frank', 'Birrell, Augustine', 'Black, Elk', 'Blair, Robert', 'Blair, Tony', 'Blake, William'];

    const aplha = people.sort(function(a,b){
      const [aFirst,aLast] = a.split(", ")
      const [bFirst,bLast] = b.split(", ")
      return aLast>bLast ? 1 : -1;
    });
    console.log(aplha)

slice()

切出数组的一个子数组。回调函数有两个参数分别是:开始和结束(不包含结束)的位置不影响原数组

    const a = [1,2,3,4,5,6]
    const b = a.slice(0,1) 
    console.log(b)   // logs [1]

splice()

在数组中增加或删除元素的方法,回调有影响原数组

    var myFish = ["angel", "clown", "mandarin", "sturgeon"];

    myFish.splice(2, 0, "drum"); 
    // myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"] 

    myFish.splice(2, 1); 
    // myFish is ["angel", "clown", "sturgeon"] 

    myFish.splice(2, 1, "splice", "parrot");
    // myFish is ["angel", "clown", "splice", "parrot", "sturgeon"]

pop()/push() && shift()/unshift()

push():是从数组尾部(索引最大的方向)加入元素,返回数组长度;
pop(): 是从数组尾部(索引最大的方向)删除元素,返回删除的元素;
shift():是从数组头部(索引最小的方向)删除元素,返回删除的元素;
unshift():是从数组头部(索引最小的方向)加入元素,返回数组长度。

自带BUFF的遍历(ES5中的方法)

forEach()

遍历数组,为每一个元素调用指定的函数。ForEach使用三个参数调用该函数分别是:数组元素,元素的索引,数组本身。修改原数组

    let a = [1,2,3,4,5]

    a.forEach((value,index,array)=> array[index] = value*value)
    console.log(a) //logs 1 4 9 16 25

当然只关心数组元素的时候,可以只写一个参数,其余的不写。现在类数组对象上面都有了forEach,但是存在浏览器的兼容问题。

map()

将调用的数组的每个元素传递给指定的函数,并返回新的数组。不影响原数组

    // 需求返回一个人全名的数组
    const inventors = [
        { first: 'Albert', last: 'Einstein', year: 1879, passed: 1955 },
        { first: 'Isaac', last: 'Newton', year: 1643, passed: 1727 },
        { first: 'Galileo', last: 'Galilei', year: 1564, passed: 1642 },
        { first: 'Marie', last: 'Curie', year: 1867, passed: 1934 },
        { first: 'Johannes', last: 'Kepler', year: 1571, passed: 1630 },
        { first: 'Nicolaus', last: 'Copernicus', year: 1473, passed: 1543 },
        { first: 'Max', last: 'Planck', year: 1858, passed: 1947 },
        { first: 'Katherine', last: 'Blodgett', year: 1898, passed: 1979 },
        { first: 'Ada', last: 'Lovelace', year: 1815, passed: 1852 },
        { first: 'Sarah E.', last: 'Goode', year: 1855, passed: 1905 },
        { first: 'Lise', last: 'Meitner', year: 1878, passed: 1968 },
        { first: 'Hanna', last: 'Hammarström', year: 1829, passed: 1909 }
        ];
    const inventorNames = inventors.map((a) => `${a.first} ${a.last}`)
    console.log(inventorNames)

filter()

返回原数组经过回调函数满足条件的一个子集。传递的函数是用来逻辑判断的:该函数返回true或false。创建新数组不影响原数组

    // 需求: 得到出生在16世纪(1500-1599)的发明家

    const sixteen = inventors.filter((inventor)=>(inventor.year >= 1500 && inventor.year < 1599))
    .map((a) => `${a.first} ${a.last}`)
    console.log(sixteen)  // "Galileo Galilei", "Johannes Kepler"

reduce()

reduce() 方法对累加器和数组的每个值 (从左到右)应用一个函数,以将其减少为单个值。

有两个参数,一个回调、一个初始值(可选)。回调有四个参数:accumulator上一次的回调返回的值,或者是初始值;currentValue数组中正在处理的元素;currentIndex正在处理元素的索引,若提供了初始值,从0开始,否则从1开始;array调用此方法的数组。初始值,其值用于第一次调用回调的第一个参数
创建新数组不影响原数组

    // 计算出同个字符出现的个数
    const string = "asdfdsasdfaaaa";
    const strArray = string.split("")
    const sum = strArray.reduce((obj,item)=>{
        if(!obj[item]){
            obj[item] = 0
        }
        obj[item]++
        
       return obj
    },{})

    console.log(sum)

indexOf()& lastIndexOf()

搜索整个数组中是否具有参数(给定值)的元素,有就返回找到的第一个元素的索引,没有就返回-1。

    const a = [4,2,3,4,8]
    const b = a.indexOf(4)   // 0 从左——> 右
    const c = a.lastIndexOf(4)  // 3  反向
    const e = a.indexOf(5)  // -1 没有

find()&findIndex()

find()/findIndex()方法返回数组中满足提供的测试函数的第一个元素的值/索引。否则返回undefined。属于ES6,有使用前请查明浏览器兼容问题

    //返回id 为 523423的text的值
    const comments = [
        { text: 'Love this!', id: 523423 },
        { text: 'Super good', id: 823423 },
        { text: 'You are the best', id: 2039842 },
        { text: 'Ramen is my fav food ever', id: 123523 },
        { text: 'Nice Nice Nice!', id: 542328 }
        ];
    const comment = comments.find(comment => comment.id === 523423)
    console.log(comment.text)
    // 删除 ID为523423的comment
    const index = comments.findIndex(comment => comment.id === 823423);
    comments.splice(index,1)
    console.table(comments);
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容