解决for循环项问题

遇到问题如下:

 var children = document.querySelectorAll('.checkbutton-bg');
                for(var i in children){
                    children[i].style.backgroundImage = 'url('+atr.norbackground+')';
                }
报错:在children[i].style中无法获取第一层“div”的backgroundImage属性。

解决方案:

 var children = document.querySelectorAll('.checkbutton-bg');
                for(var i = 0; i != children.length; i++){
                    children[i].style.backgroundImage = 'url('+atr.norbackground+')';
                }

把for循环改成for(var i = 0; i != children.length;I++)就可以了。


原因分析:

从这个问题可以看出 for(vari=0;i!= children.length;i++)  与for(variinchildren)是有区别的。

在JS中,

测试代码:

 var children = document.querySelectorAll('.checkbutton-bg');
                var k = 1;
                console.log("children.length:"+children.length)
                for(var i in children){
                /*for(var i = 0; i != children.length; i++){*/
                    /*children[i].style.backgroundImage = 'url('+atr.norbackground+')';*/

                    console.log("K:"+ k++)
                    console.log(children[i])
                }

显示:

children.length:7
directive.js:84 K:1
directive.js:85 <div ng-click=​"toggle()​" ng-transclude class=​"checkbutton-bg" selectbackground=​"img/​other/​jinbikuang1.png" norbackground=​"img/​other/​jinbikuang.png" style=​"background-image:​ url("img/​other/​jinbikuang.png")​;​ background-size:​ 100% 100%;​ background-repeat:​ no-repeat;​">​…​</div>​
directive.js:84 K:2

directive.js:84 K:7
directive.js:85 <div ng-click=​"toggle()​" ng-transclude class=​"checkbutton-bg" selectbackground=​"img/​other/​jinbikuang1.png" norbackground=​"img/​other/​jinbikuang.png" style=​"background-image:​ url("img/​other/​jinbikuang.png")​;​ background-size:​ 100% 100%;​ background-repeat:​ no-repeat;​">​…​</div>​
directive.js:84 K:8
directive.js:85 7
directive.js:84 K:9





从上面可以看出,使用 for in 数组的长度应该是7,但是循环却一直循环到8,但是没有最后一个数组元素,进而导致报错。

这是由于在for in  中i表示项的索引,也就是 0、1、2、3……  ,二不是项。

这还不是致命的,看下面的示例:

Array.prototype.copy =function () { };
var arr = [1, 2];
for (var index in arr)
{
    alert(index);
}

我们看到会弹出三个对话框,分别是:0、1、copy,也就是说除了项的数值索引 0、1,还多了一个 copy,而这个 copy 就是因为 Array.prototype.copy 扩展得到的。

所以说不要把 for (var index in items)  当作是 for (var i = 0; i < items.length; i++) 的一种简写,二者具有不同的意义。




发布了17 篇原创文章 · 获赞 5 · 访问量 6万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章