JavaScript语句末尾的[0]是什么?

时间:2014-10-04 03:01:15

标签: javascript html dom

var a = element.getElementsByTagName( 'div' ) [0]; 

我知道它会返回一个HTMLCollection,但[0]的结尾是什么意思?

1 个答案:

答案 0 :(得分:5)

getElementsByTagName返回数组,如对象而不是单个元素。所以[0]选择数组的第一个元素。

所以它就像

var i,n;
var alldivs = document.getElementsByTagName( 'div' );

//use array length to get number of matched elements
console.log("there are "+alldivs.length+" divs on the page");

//loop through each element in array
for(i=0,n=alldivs.length; i<n; i++) {
    console.log(alldivs[i]); 
}

这是a sample fiddle

注意:

这里作为消费者指出,alldivs并不完全是一个数组。意味着你做了

console.log(alldivs instanceof Array);//false
console.log([] instanceof Array);//true

所以这意味着它是一个html collection,它可以像数组一样循环,它的数组就像对象一样。但是,您不能使用Array.prototype push()pop()forEach等{{1}}上提供的常规函数​​将其视为精确数组。

相关问题