Angular应用程序中FOR循环的意外行为

Unexpected behaviour of FOR loop in Angular app

本文关键字:意外 循环 应用程序 FOR Angular      更新时间:2024-05-01

这很可能是一个愚蠢的错误,但我看不出问题。我正试图在我的Angularjs应用程序中为图像库创建一组对象。每个照片对象都有一个thumbimg属性。for循环正在很好地创建对象,我将每个对象记录到控制台以检查它们:

{thumb: "/10000/0_t.jpg", img: "/10000/0_l.jpg"}
{thumb: "/10000/1_t.jpg", img: "/10000/1_l.jpg"}
{thumb: "/10000/2_t.jpg", img: "/10000/2_l.jpg"}
...

然而,运行此代码后:

var images = [];
var image = {};
for (var i = 0; i < property.images.length; i++) {
    image.thumb = "/" + property.id + "/" + i + "_t.jpg";
    image.img = "/" + property.id + "/" + i + "_l.jpg";
    console.log(image); //this gives expected output
    images.push(image);
};
console.log(images); //this gives all entries as the same

最后的console.log给了我:

{thumb: "/10000/27_t.jpg", img: "/10000/27_l.jpg"} //X28

对于每个图像。27是因为有28张图片,但我不明白为什么它们都有相同的路径?

您需要在每次迭代中创建一个新对象:

var image;
for (var i = 0; i < property.images.length; i++) {
    image = {};
    image.thumb = "/" + property.id + "/" + i + "_t.jpg";
    image.img = "/" + property.id + "/" + i + "_l.jpg";
    console.log(image); //this gives expected output
    images.push(image);
};

如果不这样做,那么每次迭代都会重用相同的原始对象。将对象传递给.push()不会生成副本。

这个怎么样:

var path = "/" + property.id + "/";
var images = property.images.map((img,i)=>{
    return {
        thumb: path + i + "_t.jpg",
        img: path + i + "_l.jpg"
    }
});
console.log(images);

对我来说很好。请在JavaScript中尽可能限制您的范围

请参阅本书第16章通过IIFE引入新范围说JavaScript

注意: IIFE是"立即调用的函数表达式"。

var property = {
  id : 10000,
  images: [{ id: 1 }, { id: 2 }, { id: 3 }]
};
var images = [];
for (var i = 0; i < property.images.length; i++) {
  (function(){
    var image = {}; // This should be inside the loop.
                    // This way the scope does not leak.
    image.thumb = "/" + property.id + "/" + i + "_t.jpg";
    image.img = "/" + property.id + "/" + i + "_l.jpg";
    
    images.push(image);
  }());
};
document.body.innerHTML = '<pre>' + JSON.stringify(images, null, 4) + '</pre>';