簡答:這是爲了讓你有一些理智。這樣
let foo = document.getElementsByTagName('h1')
if (foo instanceof HTMLCollection)
// do something with all elements
else
// do something with just one element
如果你不知道你是否會得到一個單一的元素或元素的集合,你會寫的防守,類型檢查(笨)代碼它使更多的方式意義的功能總是返回已知類型,HTMLElement
的HTMLCollection
的對象
如果你只關心獲得的第一個元素,你可以用解構賦值
let [first] = document.getElementsByTagName('h1')
console.log(first) // outputs just the first h1
這是很好的,因爲分配清楚地表明,該公司預計元素的數組(或陣列等),但只關心第一個值
你也應該知道分配標識符更新的document.querySelector
和document.querySelectorAll
函數…
這是我怎麼會寫你的代碼在2017年
setTimeout($ => {
// get the element to change
let elem = document.querySelector('h1')
// update the text of the element
elem.textContent = 'SHUSHAN'
}, 3000)
<h1>wait 3 seconds ...</h1>
因爲返回類型是一個數組。想想如果這個函數有時返回一個en元素並且有時返回一個元素數組,那會是多麼的痛苦,那會是瘋狂的 – Keatinge