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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM