ES6 commonly used array methods (1)

Array.from The
Array.from function is used to convert array-like-objects and traversable objects (including es6 set and map) into real arrays.
Basic usage:

let people = {
    
    
	"1":"Jack",
	"2":"Alice",
	"3":"Peter",
	length:4
};

// ES5的写法
var peopleArr1 = [].slice.call(people); // [ <empty item>, 'Jack', 'Alice', 'Peter' ]


// ES6的写法
let peopleArr2 = Array.from(people); // [ undefined, 'Jack', 'Alice', 'Peter' ]

Note: The array has a length attribute, so length must be added or not, which will return an empty array

When the parameter is a true array, it will return an exactly the same array

Array.from(["Jack","Alice","Peter"])   //["Jack","Alice","Peter"]

The second parameter of Array.form, its purpose is similar to map, you can process each element, and then put it into the return array.

Array.from(people).map(item=>{
    
    item+="-"})
等同于
Array.from(people,item=>item+="-")

//["Alice-","peter-","Jack-"]

Array.of()
The parameter of Array.of is a set of values, which works to convert this set of values ​​into an array.
Basic usage:

Array.of(1,2,3,4)			//[1,2,3,4]

Argument in some similar functions

copyWithin
copyWithin can get a part of the array, and overwrite it from the specified position, and then return to the current array. Note: copyWithin will modify the current array

copyWithin receives three parameters

  1. target (number required) Cover from the specified position
  2. start (number optional) Start reading from the specified position, the default is 0, if it is a negative number, it is the reciprocal
  3. 3end (number optional) Read to the specified position to terminate, the default is the length of the array, if it is a negative number, it is the reciprocal

Basic usage:

let arr=["Alice","Peter","Jack","James","John"]
arr.copyWithin(0,3)
//["James","John","Jack","James","John"]

The above code reads from the elements of the array subscript 3 to the last element, and then starts to cover from the 0th element

find
find method is used to find an element (remember it is one) that meets the condition in the array. The parameter is a callback function until the first element that meets the condition is found, and then it is returned. If there is no element that meets the condition, it returns undefined .
Basic usage:

let arr=[3,4,5,6,7,8]
arr.find(n=>n%5===0)
//5

The above code is to get the first number divisible by 5.
If you want to get the subscript of the element that meets the conditions, you can use findIndex. The usage is basically the same. If the element that meets the condition is found, the element subscript is returned, and if it is not found, it returns -1.

let arr=[1,2,3,4,5,6]
arr.findIndex(n=>n>1)			//1
arr.findIndex(n=>n>10)			//-1

Guess you like

Origin blog.csdn.net/weixin_38987500/article/details/106713580