1. 程式人生 > >JavaScript之類陣列物件和arguments

JavaScript之類陣列物件和arguments

開發十年,就只剩下這套架構體系了! >>>   

JavaScript之類陣列物件和arguments

類陣列物件 所謂類陣列物件就是擁有一個length屬性和若干個索引屬性的物件
  1. Arguments物件就是一個類陣列物件
  2. 一個DOM方法 (document.getElementsByTagName()等)也返回類陣列物件
var array = ['name' , 'age' , 'hy'] // 陣列

var arrayLike = { // 類陣列
    0:'name',
    1:'age',
    2:'hy',
    length:3
}

讀寫

console.log(array[0]) // name
console.log(arrayLike[0]) // name

array[0] = 'ycl'
arrayLike[0] = 'ycl'

長度

console.log(array.length) // 3
console.log(arrayLike.length) // 3

那類陣列物件能不能使用陣列的方法嗎 ? 比如
arrayLike.push('4’). // arrayLike.push is not a function

 

如果類陣列物件想呼叫陣列的方法該怎麼辦 ?
var arrayLike = { // 類陣列
    0:'name',
    1:'age',
    2:'hy',
    length:3
}

console.log(Array.prototype.join.call(arrayLike,'&’)). // name&age&hy

console.log(Array.prototype.slice.call(arrayLike)) // [ 'name', 'age', 'hy' ]

console.log(Array.prototype.map.call(arrayLike , function(item){ // [ 'NAME', 'AGE', 'HY' ]
     return item.toUpperCase()
}))

 

類陣列轉陣列
console.log(Array.prototype.slice.call(arrayLike)).

console.log(Array.prototype.splice.call(arrayLike , 0)). // 會改變原陣列

console.log(Array.from(arrayLike)) // es6 Array.from

Arguments物件

Arguments物件只定義在函式體中,包括了函式的引數和其他屬性,arguements 代指 函式的Arguments物件   使用es6的 …運算子 ,我們可以輕鬆轉換為陣列
function func(...arguments){
    console.log(arguments)
}
func(1, 2, 3). // [ 1, 2, 3 ]