js的from方法

from的语法如下

Array.from(object, mapFunction, thisValue)

object为要转为数组的对象,此对象的必须有length值,或为set()得到的对象,或字符串(必须参数)

如果object是一个数组,返回的仍是此数组

 let arrayLike = {
 0: 'tom', 
 1: '65',
 2: '男',
 3: ['jane','john','Mary'],
 'length':2
}
let arr2 = Array.from(arrayLike)//["tom", "65"]
let arr = [12,45,97,9797,564,134,45642]
let set = new Set(arr)
console.log(Array.from(set)) // [ 12, 45, 97, 9797, 564, 134, 45642 ]

mapFunction,处理object的map函数(非必须参数)

a = [{a: "1", b: 9},{a: "2", b: 8},{a: "3", b: 7}];
b= Array.from(a,function (x) {
    return x.b;
});
//b[0] == 9;
//b[1] == 8;
//b[2] == 7;

thisValue,map函数中this指向的对象(非必须参数)

let diObj = {
  handle: function(n){
    return n + 2
  }
}
 
console.log('%s', Array.from(
  [1, 2, 3, 4, 5], 
  function (x){
    return this.handle(x)
  }, 
  diObj))

结果为3,4,5,6,7

猜你喜欢

转载自www.cnblogs.com/ybhome/p/11793841.html