1、Array.from()
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 length
property 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 this
pointing object, somewhat similar bind
, , call
, apply
the 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 key
is a numerical value, and value
not digital, it can be regarded as an object-based array, key
is 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, instanceof
for 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. of
The method is to each parameter item in the array as the inside, if only a number key parameter is still an array
2. Array
Each parameter will constructor inside as the entry array, if only one digital parameter that will create an empty array length