什麼是 array-like object

HsinYun
4 min readMar 11, 2024

--

學 TS 到「陣列的型別」章節時,看到 array-like object 這個詞。拉一小篇出來討論。

1. Array

是一個索引的集合(indexed collection),可以保存任何類型的資料,我們可以透過 index 來取得元素。

const array = [1, "2", {a: 3}, null, true]
console.log(array[3]) // null

2. Object

鍵的集合(keyed collection),以 key : value 形式保存屬性,可以用 .[] 來取值。

const object = { 
id: 12345,
created_time: "Jan, 2023"
}

console.log(object.id) // 12345
console.log(object["created_time"]) // Jan, 2023

3. Array-like object

其實就是 object。可以用 index 取值,也可以用 .length 來獲得長度,但他沒有其他 array 的方法。


const arrayLikeObject = {
0: 'value1',
1: 'value2',
2: 'value3',
length: 3
}

console.log(arrayLikeObject[1]) // value2
console.log(arrayLikeObject.length) // 3

console.log(arrayLikeObject.1) // 錯誤,數字開頭的 key 無法用 . 來取得值,這使他跟 array 很相似

arrayLikeObject.push({3: 'value4'}) // 錯誤,Uncaught TypeError: arrayLikeObject.push is not a function

這種 object 常見於這幾個地方:函數中的 argument 物件、DOM NodeList、HTMLCollection。

(1) 函數中的 arguments

function showArguments() {
console.log('Number of arguments:', arguments.length);
console.log('The second argument is:', arguments[1]);
console.log(arguments)
}

showArguments('Hello', 'World', 42);

// Number of arguments: 3
// The second argument is: World
// 第三個結果為以下截圖
在 showArguments() 函數中 console.log(arguments) 的結果

每個 JS 函數內部都有一個 arguments 物件,這個物件包含了呼叫函數時傳遞給它的所有參數。arguments 物件是一個 array-like object,擁有一個 length 屬性和索引屬性,讓你可以像操作陣列一樣使用傳遞給函數的每個參數。

(2) DOM NodeList 或 HTML collection

這是我在瀏覽器 console 嘗試的結果

var divs = document.querySelectorAll('div'); // 這是一個 array-like object

console.log(divs) // NodeList(94)
console.log(divs.length) // 94
console.log(typeof divs) // object
const list = document.getElementsByTagName('li'); // 這也是一個 array-like object

console.log(list.length) // 8

轉換成真・陣列

將 array-like object 轉換成 array 有很多種方式,以下舉例三種:

  • Array.prototype.slice.call()
  • Array.from()
  • 展開運算符 (Spread operator)
const list = document.getElementsByTagName('li');

console.log(Array.prototype.slice.call(list))
console.log(Array.from(list))
console.log([...list])

// array(8)

--

--