关于数组函数,众所周知,我们可以通过Array函数做以下事情。
// 1. Initialize an array of the specified lengthconst array1 = Array(3) // [ , , ]// 2. Set the initial value of the arrayconst array2 = Array() // []const array3 = Array(undefined) // [ undefined ]const array4 = Array(1, 2, 3) // [ 1, 2, 3 ]
传递给Array函数的参数个数不一样,其功能也不一样。这常常让我感到困惑。
幸运的是,我们可以使用Array.of来弥补Array的缺点。
// it's not initializing an array of length 3const array1 = Array.of(3) // [ 3 ]const array2 = Array.of() // []const array3 = Array.of(undefined) // [ undefined ]const array4 = Array.of(1, 2, 3) // [ 1, 2, 3 ]
在该方法中,我们可以通过 Array.from 方法将类数组对象、arguments 对象和 NodeList 对象转换为真正的数组。
类似数组的对象
const arrayLike = { 0: 'fatfish', 1: 'medium', length: 2}const array1 = [].slice.call(arrayLike) // ['fatfish', 'medium']// A more convenient wayconst array2 = Array.from(arrayLike) // ['fatfish', 'medium']
const domsNodeList = document.querySelectorAll('div')const domsArray = Array.from(domsNodeList) // [ dom, dom, dom, ... ]
const logInfo = function () { console.log('arguments', arguments) console.log('Array.from arguments', Array.from(arguments))}logInfo('fatfish', 100)logInfo('fatfish')
我们可以使用 Array.from 方法,例如“[].map”。
const array = [ 1, 2, 3 ]const array2 = array.map((num) => num * 2) // [2, 4, 6]const array3 = Array.from(array, (num) => num * 2) // [2, 4, 6]
我们经常会写这样的判断语句,当其中一个条件满足时做某事。
const num = 1if (num === 1 || num === 2 || num === 3 || num === 4) { console.log(num) // 1}
其实可以通过include方法来简化代码。
const nums = [ 1, 2, 3, 4 ]const num = 1if (nums.includes(num)) { console.log(num) // 1}
如何读取数组的尾部元素?是的,我们需要以“array.length-1”作为下标来读取。
const array = [ 1, 2, 3, 4, 5 ]const lastEle = array[ array.length - 1 ] // 5// You can't read like thatconst lastEle = array[ - 1 ] // undefined
还有其他办法吗?
是的,“at”方法将是你的魔力。当然,您可以读取数组中其他位置的元素。
const array = [ 1, 2, 3, 4, 5 ]const lastEle = array.at(-1) // 5const ele1 = array.at(0) // 1
来自 MDN:“flat() 方法创建一个新数组,其中所有子数组元素递归地连接到其中,直到指定的深度。”
const array = [ 1, [ 2, [ 3, [ 4, [ 5 ] ] ] ] ]// The default depth is 1const flat1 = array.flat() // [ 1, 2, [ 3, [ 4, [ 5 ] ] ] ]const flat2 = array.flat(2) // [ 1, 2, 3, [ 4, [ 5 ] ] ]const flatAll = array.flat(Infinity) // [ 1, 2, 3, 4, 5 ]
来自 MDN:“findIndex() 方法返回数组中满足所提供的测试函数的第一个元素的索引。否则,返回-1,表示没有元素通过测试。”
const array = [ -1, 0, 10, 10, 20, 100 ]const index1 = array.findIndex((num) => num < 0) // 0const index2 = array.findIndex((num) => num >= 10) // 2
本文链接:http://www.28at.com/showinfo-26-58895-0.html六个你必须知道的 ES6 中很酷的数组函数
声明:本网页内容旨在传播知识,不代表本站观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。