For .. in循环无法设置未定义的属性 [英] For.. in loop cannot set property of undefined
问题描述
var table = document.querySelectorAll(".numbers");
function seppuku() {
for (let i in table) {
table[i].style.color = "red";
}
}
seppuku();
<div class="numbers">1</div>
<div class="numbers">2</div>
<div class="numbers">3</div>
这是我的代码.我的问题是:为什么seppuku()函数调用后console.log会传达无法设置未定义的属性'颜色'"?
So here's my code. My problem is: Why console.log communicate "Cannot set property 'color' of undefined" after seppuku() function invoking?
这不像未定义var表!实际上,它具有全局范围,应可用于"for .. in"循环.此外,此功能有效,所选元素现在具有颜色:红色属性.尽管在控制台中进行了通信,该如何工作?
It's not like var table is not defined! Actually, it has global scope and should be available for 'for.. in' loop. Moreover, this function works, chosen elements has color: red property now. How that works despite the communicate in console?
推荐答案
您使用了 for ... in
语句,该语句遍历对象的可枚举属性.在这种情况下, table
对象包含以下枚举属性.
You used for...in
statement which iterates over the enumerable properties of an object. In this case, table
object contains following enumerable properties.
{
"0": <div class="numbers">1</div>,
"1": <div class="numbers">2</div>,
"2": <div class="numbers">3</div>,
"length": 3,
"item": function item() { [native code] },
"entries": function entries() { [native code] },
"forEach": function forEach() { [native code] },
"keys": function keys() { [native code] },
"values": function values() { [native code] }
}
因此,在第4次迭代中, i
变为 length
,并且table ['length'].style引发错误.我们可以使用 forEach
方法来解决此问题.
So in the 4th iteration, i
becomes length
and table['length'].style throws an error. We can use forEach
method to resolve this issue.
var table = document.querySelectorAll(".numbers");
(function seppuku() {
table.forEach(function(item) {
item.style.color = "red";
});
})();
<div class="numbers">1</div>
<div class="numbers">2</div>
<div class="numbers">3</div>
这篇关于For .. in循环无法设置未定义的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!