关于javascript:JS30Wes-Bos数组操作-04

55次阅读

共计 2378 个字符,预计需要花费 6 分钟才能阅读完成。


title:【原生 javascript 我的项目】数组操作 04
date: 2021-11-15 19:30:39
tags: 原生 javascript 我的项目
categories: 30 个原生 javascript 我的项目


引言

本文介绍一下数组操作的一些罕用办法。

注释

1 创立数组

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

2 获取数组长度

console.log(people.length);

3 循环

people.forEach(function(item,index){console.log(item,index);
})

4 数据尾部增加一个元素

let newLength = people.push('Wheeler, Ben');// newLength 的后果是 people 的长度,不是新增加的元素内容
console.log(people.length);

5 从尾部删除一个元素

let last = people.pop();
console.log(people.length);

6 从头部删除一个元素

let first = people.shift();
console.log(people.length);

7 从提增加一个新元素

let firstItem = people.unshift('Bernhard, Sandra');
console.log(people);

8 寻找下标

let pos = people.indexOf('Blair, Tony');
console.log(pos);

9 依据下标删除元素

let removeItem = people.splice(pos,1);// 参数 1 示意 Pos 下标后多少个 console.log(removeItem);

10 复制数组

// 复制数组 1let newPeople1 = people; //people 和 newPeople1 指向同一个内存 // 复制数组 2let newPeople2 = people.slice(); // people 和 newPeople1 指向不同一个内存 

11 Index 超出数组长度

people[100] = 'bbb';console.log(people);

12 Array.prototype.filter() 过滤

const fifteen = inventors.filter(inventor=>(inventor.year>=1500 && inventor.year < 1600));console.table(fifteen);

13 Array.prototype.map()

const fullNames = inventors.map(inventor => (inventor.first + ' ' + inventor.last));const fullNames2 = inventors.map(inventor => `${inventor.first} ${inventor.last}`);console.log(fullNames);console.log(fullNames2);

14 Array.prototype.sort()

// 升序 const ordered = inventors.sort((a,b) => a.year > b.year ? 1 : -1);console.table(ordered);// 降序 const oldest = inventors.sort(function(a,b){const lastInventor = a.passed - a.year;    const nextInventor = b.passed - b.year;    return lastInventor > nextInventor ? -1:1;});console.table(oldest);

15 Array.prototype.reduce() 后果返回单个值

// Array.prototype.reduce() 后果返回单个值 const totalYears = inventors.reduce((total,inventor) => {return total + (inventor.passed - inventor.year);}, 0); // 0 示意返回的单个值再加上 0console.log(totalYears);            

论断

残缺代码放在了 Github 上,如果读者有趣味,无妨试一试。

正文完
 0