做者:Bolaji Ayodeji翻译:疯狂的技术宅javascript
原文:https://www.freecodecamp.org/...前端
未经容许严禁转载java
在开始以前,你须要先了解数组的真正含义。程序员
在 JavaScript 中,数组是一个用于存储不一样数据类型的变量。它将不一样的元素存储在一个盒子中,供之后使用。
声明一个数组:面试
let myBox = []; // JS中的初始化数组声明
数组中能够包含多种数据类型算法
let myBox = ['hello', 1, 2, 3, true, 'hi'];
能够用被称为方法的多个操做来操做数组。这些方法容许咱们对数组进行添加、删除、修改挤执行更多操做。chrome
我会在本文中向你展现一其中的一部分,让咱们继续:segmentfault
注意:本文中使用了箭头功能,若是你不知道这意味着什么,你应该在这里阅读。箭头功能是ES6的功能。
toString()
方法可以将数组转换为以逗号分隔的字符串。数组
let colors = ['green', 'yellow', 'blue']; console.log(colors.toString()); // green,yellow,blue
The JavaScript join()
method combines all array elements into a string.
JavaScript 的 join()
方法将全部数组元素组合成一个字符串。服务器
它相似于 toString()
方法,但在这里你能够指定分隔符而不是默认的逗号。
let colors = ['green', 'yellow', 'blue']; console.log(colors.join('-')); // green-yellow-blue
此方法能够将两个数组组合在一块儿,或者向数组中添加更多的元素项,而后返回一个新数组。
let firstNumbers = [1, 2, 3]; let secondNumbers = [4, 5, 6]; let merged = firstNumbers.concat(secondNumbers); console.log(merged); // [1, 2, 3, 4, 5, 6]
此方法将元素项添加到数组的末尾,并修改原始数组。
let browsers = ['chrome', 'firefox', 'edge']; browsers.push('safari', 'opera mini'); console.log(browsers); // ["chrome", "firefox", "edge", "safari", "opera mini"]
此方法删除数组的最后一项并返回。
let browsers = ['chrome', 'firefox', 'edge']; browsers.pop(); // "edge" console.log(browsers); // ["chrome", "firefox"]
此方法删除数组的第一项,并将它返回。
let browsers = ['chrome', 'firefox', 'edge']; browsers.shift(); // "chrome" console.log(browsers); // ["firefox", "edge"]
此方法将一个项添加到数组的开头,并修改原始数组。
let browsers = ['chrome', 'firefox', 'edge']; browsers.unshift('safari'); console.log(browsers); // ["safari", "chrome", "firefox", "edge"]
你还能够一次添加多个项目
此方法经过添加、删除和插入元素来修改数组。
语法是:
array.splice(index[, deleteCount, element1, ..., elementN])
Index
这里是删除数组中元素的起点deleteCount
是要从该索引中删除的元素数element1, …, elementN
是要添加的元素运行splice()后,它返回删除项目以后的数组,而且被删除的项目将其从原始数组中删除。
let colors = ['green', 'yellow', 'blue', 'purple']; colors.splice(0, 3); console.log(colors); // ["purple"] // deletes ["green", "yellow", "blue"]
注意: deleteCount 不包括范围内的最后一个索引。
若是没有声明第二个参数,则将会从数组中删除从给定索引开始的全部元素:
let colors = ['green', 'yellow', 'blue', 'purple']; colors.splice(3); console.log(colors); // ["green", "yellow", "blue"] // deletes ['purple']
在下一个例子中,咱们将从数组中删除 3 个元素,并用更多的项去替换它们:
let schedule = ['I', 'have', 'a', 'meeting', 'tommorrow']; // removes 4 first elements and replace them with another schedule.splice(0, 4, 'we', 'are', 'going', 'to', 'swim'); console.log(schedule); // ["we", "are", "going", "to", "swim", "tommorrow"]
要添加项目,咱们须要将 deleteCount
设置为零
let schedule = ['I', 'have', 'a', 'meeting', 'with']; // adds 3 new elements to the array schedule.splice(5, 0, 'some', 'clients', 'tommorrow'); console.log(schedule); // ["I", "have", "a", "meeting", "with", "some", "clients", "tommorrow"]
此方法与 splice() 有点像,可是有很大不一样。它返回子数组而不是子字符串。
此方法复制数组的给定部分,并将复制的部分做为新数组返回。 它不会改变原始数组。
语法是:
array.slice(start, end)
这是一个简单的例子:
let numbers = [1, 2, 3, 4] numbers.slice(0, 3) // returns [1, 2, 3] console.log(numbers) //返回原始数组
使用 slice()
的最好方式是将它分配给一个新变量。
let message = 'congratulations' const abbrv = message.slice(0, 7) + 's!'; console.log(abbrv) // 返回 "congrats!"
此方法用于字符串。它将一个字符串分红子串并将它们做为数组返回。
语法:string.split(separator, limit);
separator
定义了如何分割字符串。let firstName = 'Bolaji'; // return the string as an array firstName.split() // ["Bolaji"]
另外一个例子:
let firstName = 'hello, my name is bolaji, I am a dev.'; firstName.split(',', 2); // ["hello", " my name is bolaji"]
注意:若是咱们声明一个空数组,好比 firstName.split('');
,那么字符串中的每一个项目将都会被分割为子字符串:
let firstName = 'Bolaji'; firstName.split('') // ["B", "o", "l", "a", "j", "i"]
此方法在数组中查找项目,若是它被找到就返回索引,不然返回 -1
let fruits = ['apple', 'orange', false, 3] fruits.indexOf('orange'); // returns 1 fruits.indexOf(3); // returns 3 friuts.indexOf(null); // returns -1 (not found)
这种方法的工做方式与 indexOf() 相同,只是它从右到左工做。它返回找到的最后一个索引
let fruits = ['apple', 'orange', false, 3, 'apple'] fruits.lastIndexOf('apple'); // returns 4
若是数组的项目符合某个条件,则此方法将会建立一个新数组。
语法是:
let results = array.filter(function(item, index, array) { // returns true if the item passes the filter });
例:经过区号检查来自 Nigeria 的用户
const countryCode = ['+234', '+144', '+233', '+234']; const nigerian = countryCode.filter( code => code === '+234'); console.log(nigerian); // ["+234", "+234"]
此方法经过操做数组中的值来建立新数组。
例:显示页面上的用户名。 (基本好友列表显示)
const userNames = ['tina', 'danny', 'mark', 'bolaji']; const display = userNames.map(item => { return '<li>' + item + '</li>'; }) const render = '<ul>' + display.join('') + '</ul>'; document.write(render);
另外一个例子:
// 将美圆符号添加到数字前面 const numbers = [10, 3, 4, 6]; const dollars = numbers.map( number => '$' + number); console.log(dollars); // ['$10', '$3', '$4', '$6'];
此方法适用于计算总计的值。
reduce() 用于计算数组中的单个值。
let value = array.reduce(function(previousValue, item, index, array) { // ... }, initial);
例:
要遍历数组并对数组中的全部数字求和,可使用 for 循环。
const numbers = [100, 300, 500, 70]; let sum = 0; for (let n of numbers) { sum += n; } console.log(sum);
如下是用 reduce()
实现相同g功能的方法
const numbers = [100, 300, 500, 70]; const sum = numbers.reduce( (accummulator, value) => accummulator + value , 0); console.log(sum); // 970
若是省略初始值,默认状况下总数将从数组中的第一项开始计算。
const numbers = [100, 300, 500, 70]; const sum = numbers.reduce((accummulator, value) => accummulator + value); console.log(sum); // still returns 970
下面的代码段显示了 reduce() 方法如何与全部四个参数一块儿使用。
来源:MDN Docs
有关 reduce() 的各类用法的更多说明能够在 这里 和 这里 找到。
此方法适用于迭代数组。
它把函数做用于数组中的全部项
const colors = ['green', 'yellow', 'blue']; colors.forEach((item, index) => console.log(index, item)); // returns the index and the every item in the array // 0 "green" // 1 "yellow" // 2 "blue"
迭代无需不传递索引参数便可完成
const colors = ['green', 'yellow', 'blue']; colors.forEach((item) => console.log(item)); // returns every item in the array // "green" // "yellow" // "blue"
此方法检查数组中的全部项是否都符合指定的条件,若是符合则返回 true
,不然返回 false
。
检查全部数字是否为正
const numbers = [1, -1, 2, 3]; let allPositive = numbers.every((value) => { return value >= 0; }) console.log(allPositive); // would return false
此方法检查数组中的项(一个或多个)是否符合指定的条件,若是符合则返回true,不然返回false。
检查至少有一个数字是否为正
const numbers = [1, -1, 2, 3]; let atLeastOnePositive = numbers.some((value) => { return value >= 0; }) console.log(atLeastOnePositive); // would return true
此方法检查数组是否包含某个项目。它相似于 .some()
,但它不是要查找符合的特定条件,而是检查数组是否包含特定项。
let users = ['paddy', 'zaddy', 'faddy', 'baddy']; users.includes('baddy'); // returns true
若是找不到该项,则返回 false
关于数组方法还有有更多,这只是其中的一部分。此外,还有大量能够在数组上执行的其余操做,请经过查看 MDN 文档 来得到更深刻的信息。
-1
true
,不然返回 false
。数组是强大的,经过相关的方法能够编写实用的算法。
让咱们写一个小函数,一个将文章标题转换为 urlSlug 的函数。
URL slug是你网站上特定网页或文章的确切地址。
当你在 Freecodecamp News 或任何其余博客平台上撰写文章时,你的文章标题会自动转换为一个 slug,其中删除了空格,字符变为小写,标题中的每一个单词都用连字符分隔。
这是一个基本功能,能够用咱们刚才学到的一些方法来作到这一点。
const url = 'https://bolajiayodeji.com/' const urlSlug = (postTitle) => { let postUrl = postTitle.toLowerCase().split(' '); let postSlug = `${url}` + postUrl.join('-'); return postSlug; } let postTitle = 'Introduction to Chrome Lighthouse' console.log(urlSlug(postTitle)); // https://bolajiayodeji.com/introduction-to-chrome-lighthouse
在 postUrl
中,咱们先将字符串转换为小写,而后用 split() 方法将字符串转换为子字符串并将其返回到数组中
["introduction", "to", "chrome", "lighthouse"]
在 post slug
中,用连字符链接返回的数组,而后将它与类别字符串和主 url
链接到一块儿。
let postSlug = `${url}` + postUrl.join('-'); postUrl.join('-') // introduction-to-chrome-lighthouse
就是这样,很是简单,对吧?😄