阿里云主机折上折
  • 微信号
Current Site:Index > Extension methods for arrays

Extension methods for arrays

Author:Chuan Chen 阅读数:8040人阅读 分类: JavaScript

Spread Operator for Arrays

The spread operator (spread) is represented by three dots (...). It acts as the inverse of rest parameters, converting an array into a sequence of comma-separated arguments.

console.log(...[1, 2, 3]) // 1 2 3
console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5

The spread operator is primarily used for function calls:

function add(x, y) {
  return x + y
}
const numbers = [4, 38]
add(...numbers) // 42

It can replace the apply method for arrays:

// ES5 syntax
Math.max.apply(null, [14, 3, 77])

// ES6 syntax
Math.max(...[14, 3, 77])

Other applications of the spread operator include:

  • Copying arrays
  • Merging arrays
  • Combining with destructuring assignment
  • Converting strings to arrays
  • Objects that implement the Iterator interface

Array.from()

The Array.from method is used to convert two types of objects into true arrays: array-like objects and iterable objects (including ES6's new Set and Map data structures).

let arrayLike = {
  '0': 'a',
  '1': 'b',
  '2': 'c',
  length: 3
}

// ES5 syntax
var arr1 = [].slice.call(arrayLike) // ['a', 'b', 'c']

// ES6 syntax
let arr2 = Array.from(arrayLike) // ['a', 'b', 'c']

Array.from can also accept a second parameter, which functions similarly to the array's map method:

Array.from(arrayLike, x => x + x)
// ['aa', 'bb', 'cc']

Array.of()

The Array.of method converts a set of values into an array.

Array.of(3, 11, 8) // [3,11,8]
Array.of(3) // [3]
Array.of(3).length // 1

This method primarily addresses the shortcomings of the array constructor Array():

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8) // [3, 11, 8]

Array Instance's copyWithin()

The copyWithin method of array instances copies specified members within the array to other positions (overwriting existing members) and returns the modified array.

[1, 2, 3, 4, 5].copyWithin(0, 3)
// [4, 5, 3, 4, 5]

copyWithin accepts three parameters:

  • target (required): The position to start replacing data.
  • start (optional): The position to start reading data, defaults to 0.
  • end (optional): The position to stop reading data (exclusive), defaults to the array length.

Array Instance's find() and findIndex()

The find method returns the first array member that meets the specified condition. It takes a callback function, which is executed for each member until the first true is returned. If no member meets the condition, it returns undefined.

[1, 4, -5, 10].find((n) => n < 0)
// -5

The findIndex method is similar to find but returns the index of the first qualifying member. If no member meets the condition, it returns -1.

[1, 5, 10, 15].findIndex(function(value, index, arr) {
  return value > 9
}) // 2

Array Instance's fill()

The fill method fills an array with a given value.

['a', 'b', 'c'].fill(7)
// [7, 7, 7]

new Array(3).fill(7)
// [7, 7, 7]

fill can also accept a second and third parameter to specify the start and end positions for filling.

['a', 'b', 'c'].fill(7, 1, 2)
// ['a', 7, 'c']

Array Instance's entries(), keys(), and values()

ES6 provides three new methods—entries(), keys(), and values()—for traversing arrays. Each returns an iterator object that can be traversed using for...of.

keys() iterates over the keys:

for (let index of ['a', 'b'].keys()) {
  console.log(index)
}
// 0
// 1

values() iterates over the values:

for (let elem of ['a', 'b'].values()) {
  console.log(elem)
}
// 'a'
// 'b'

entries() iterates over key-value pairs:

for (let [index, elem] of ['a', 'b'].entries()) {
  console.log(index, elem)
}
// 0 "a"
// 1 "b"

Array Instance's includes()

The Array.prototype.includes method returns a boolean indicating whether an array includes a given value, similar to the string includes method.

[1, 2, 3].includes(2)     // true
[1, 2, 3].includes(4)     // false
[1, 2, NaN].includes(NaN) // true

The second parameter specifies the starting position for the search (defaults to 0):

[1, 2, 3].includes(3, 3)  // false
[1, 2, 3].includes(3, -1) // true

Array Instance's flat() and flatMap()

The flat() method "flattens" nested arrays into a one-dimensional array. It returns a new array without modifying the original.

[1, 2, [3, 4]].flat()
// [1, 2, 3, 4]

By default, flat() only flattens one level. To flatten multiple levels, pass an integer as the parameter:

[1, 2, [3, [4, 5]]].flat(2)
// [1, 2, 3, 4, 5]

The flatMap() method first maps each element of the array (like Array.prototype.map()) and then flattens the result. It returns a new array without modifying the original.

[2, 3, 4].flatMap((x) => [x, x * 2])
// [2, 4, 3, 6, 4, 8]

Array Gaps

ES6 explicitly converts array gaps to undefined.

Array.from(['a',,'b'])
// [ "a", undefined, "b" ]

[...['a',,'b']]
// [ "a", undefined, "b" ]

Methods like Array.from, the spread operator, copyWithin(), fill(), entries(), keys(), values(), and find() all treat gaps as undefined.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:常见使用模式

下一篇:对象的扩展方法

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.