在我的页面中有几个img标记,如下所示:
<img class="img-fluid meeseks" src="img/meeseks_red.jpg" data-color="#ee5b61" />在js文件中,我创建了以下内容:
function Store(path,color){
this.path=path
this.color=color}然后,开始编写代码,我写了如下:
img_path=[]
for (var i=0;i<img.length;i++){
img_path.push( new Store(img[i].getAttribute("src"),img[i].getAttribute("data-color")))
}若要获取存储每个图像的src和颜色的对象数组,请执行以下操作。
现在,研究生活,我写了这个似乎也很管用的东西:
(function store_inf(){
img_path=[]
for (var i=0;i<img.length;i++){
img_path.push( new Store(img[i].getAttribute("src"),img[i].getAttribute("data-color")))
}
return img_path
})()在这种情况下哪条路更好?我还注意到,如果我省略了,返回的东西正常工作(如果我记录img_path数组,我总是有一个对象数组)
那么,在全局范围内,即使在调用IIFE之后,IIFE也返回一个永久的数组?谢谢
发布于 2017-06-22 18:58:09
您当前的代码可以工作,因为img_path实际上是全局的,而且您的生活是无用的。你可以这样做:
var img_path=(function(){
var img=document.getElementByTagName("img");
var img_path=[];//now local
for (var i=0;i<img.length;i++){
img_path.push( new Store(img[i].getAttribute("src"),img[i].getAttribute("data-color")))
}
return img_path
})()现在有一个封闭的img_path和img数组以及一个全局img_path。
请注意,您还可以:
var img_path=document.querySelectorAll("img").values().map(el=>new Store(el.src,el.getAttribute("data-color")));发布于 2017-06-22 18:56:37
img_path之所以是全球性的,与生活无关。它是全局的,因为您没有用var关键字声明它。没有用var (或const或let)声明的所有内容都将附加到全局范围,在您的示例中,它将附加到window对象。只需在你的生活(或不是生活)代码版本之后尝试console.log(window.img_path)。
我建议您开始在js中使用use strict,因为它会指出更多“不明显”的错误。
发布于 2017-06-22 18:59:56
你应该多关心分号,它们不是用来休闲的,而是因为你需要分号。在没有分号的情况下引入歧义是有边的。也就是说,如果您不以任何方式使用结果(作为参数或赋值),则不需要函数namen,也不需要返回任何内容。您也不需要存储函数,它实际上没有什么作用,只需使用JS对象文本,如下所示。这一职能也可以写成:
(function () {
"use strict";
var i, img_path;
img_path = [];
for (i = 0; i < img.length; i++)
{
img_path.push({
"path": img[i]["src"],
"color": img[i]["data-color"]
});
}
// TODO: use img_path here because outside this function scope it does not exist
}());
// ^ better parens placement有关如何编写干净的代码和遵循开源JS风格的更多信息,请查找JSLint和类似工具。您将看到这种工具会给您带来多少样式错误。
https://stackoverflow.com/questions/44707281
复制相似问题