Javascript - Array method of learning

1、Array.from()

references

This method is interesting, can be an iterative or a similar array of object segmentation, then the value returned as a new array

Pseudo array of objects (has a lengthproperty and a number of indexes attributes for any object)

Iterables] ( https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/iterable ) (the elements may acquire the object, such as Map Set and the like)

This method has three parameters, one is the first to be converted into an array or an array of dummy iterables, the second parameter is the equivalent of a map method, the third parameter is the function executed inside the map when the thispointing object, somewhat similar bind, , call, applythe method can separate the object data and processing data

const DObj = {
  handleArr: function (x) {
    return x+'1'
  }
}
Array.from('Hello World !',function (v) { return this.handleArr(v)}, DObj)

// 打印结果
["H1", "e1", "l1", "l1", "o1", " 1", "W1", "o1", "r1", "l1", "d1", " 1", "!1"]

Tips when using the third parameter, map function Do not use the arrow functions, otherwise this point does not change, does not involve a third parameter, you can use the arrow functions

Map

let m = new Map()
m.set('one', 'H')
m.set('tow', 'a')
m.set('three', 'a')
const DObj = {
  handleArr: function (x) {
    return x + '1'
  }
}
newData = Array.from(m, function (v) { return this.handleArr(v)}, DObj)
console.log( newData)
// 打印结果
["one,H1", "tow,a1", "three,a1"]

Set

let m = new Set()
m.add('H')
m.add('a')
m.add('o')
const DObj = {
  handleArr: function (x) {
    return x + '1'
  }
}
newData = Array.from(m, function (v) { return this.handleArr(v)}, DObj)
console.log( newData)
// 打印结果
["H1", "a1", "o1"]

Class array of objects

As long as the object keyis a numerical value, and valuenot digital, it can be regarded as an object-based array, keyis the index

2、Array.isArray()

This method is used to detect whether a variable is an array data or, if it returns true, otherwise it returnsfalse

const arr = [1,2,3,4,5];
const obj = {name: '李狗蛋'};
const str = 'Hello World';
console.log(Array.isArray(arr))
console.log(Array.isArray(str))
console.log(Array.isArray(obj))

// 打印结果
true
false
false

Tips typeof used to detect the type of data or variables, but only return types, is not accurate, instanceoffor instance detecting whether a data variable or an object, but also returns the arraytrue

3、Array.of()

The Array constructor and put a somewhat similar, you can create an array of parameters based on inside, but the difference is:

1. ofThe method is to each parameter item in the array as the inside, if only a number key parameter is still an array

2. ArrayEach parameter will constructor inside as the entry array, if only one digital parameter that will create an empty array length

Guess you like

Origin www.cnblogs.com/zjh-study/p/10958455.html