Javascript -- 數組方法學習

一、Array.from()

參考文獻數組

這個方法比較有意思,能夠將一個相似數組或可迭代對象分割,而後將值返回爲一個新數組app

僞數組對象(擁有一個 length 屬性和若干索引屬性的任意對象)ide

可迭代對象](https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/iterable)(能夠獲取對象中的元素,如 Map和 Set 等)函數

這個方法有三個參數,第一個就是要轉換成數組的僞數組或者可迭代對象,第二個參數就是至關於一個map方法,第三個參數就是map函數執行時裏面的的this指向對象,有點相似bindcallapply,能夠將數據和處理數據的對象方法分開ui

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 使用第三個參數時,map函數方法不要使用箭頭函數,不然this指向不會改變,若是不涉及第三個參數,可使用箭頭函數this

Mapcode

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"]

類數組對象索引

只要對象的key是數值,而且value不能爲數字,就能夠視做類數組對象,key就是索引three

二、Array.isArray()

這個方法是用來檢測某個數據或者變量是不是數組,若是是則返回true,不然返回false

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用來檢測數據或變量的類型,可是隻是返回個類型,並不精準,instanceof用來檢測數據或者變量是否某個對象的實例,可是數組也會返回true

三、Array.of()

這個放個和Array構造函數有點相似,均可以根據裏面的參數建立數組,不過不一樣的是:

1.of方法是把裏面的每個參數做爲數組的項,若是隻是一個數字參數,依舊也是一個數組的項

2.Array構造函數會把裏面的每個參數做爲數組的項,若是隻是一個數字參數,則會建立一個該長度的空數組

相關文章
相關標籤/搜索