【发布时间】:2018-07-16 06:12:23
【问题描述】:
box = {
curBox: 0,
boxes: document.getElementsByClassName('box'),
size: this.boxes.length, //this one won't work
orSize: Object.keys(this.boxes).length, //as well as this one
preBox: function() {
curBox -= 1
},
nexBox: function() {
curBox += 1
}
}
console.log(box.boxes.length); //This one works well!!!
<div class='active box BG_blue'>
<meta name='title' content='Overview' /> ...
</div>
<div class='inactive box BG_orange'>
<meta name='title' content='Career' /> ...
</div>
<div class='inactive box BG_red'>
<meta name='title' content='Skills' /> ...
</div>
<div class='inactive box BG_awesome'>
<meta name='title' content='Hobbies' /> ...
</div>
我试图获取从getElementsByClassName 返回的数组的长度。如果我把它放在对象范围之外,它就可以工作。但在对象范围内,它不会。现在,我想知道一个原因。我在其他站点(例如Mozilla)代码编辑器上进行了测试,但它只返回相同的结果。
【问题讨论】:
-
因为
this不指向box对象。this指向窗口对象
标签: javascript arrays object variable-length-array