嵌套的“for”循环 - 打字稿角度

时间:2021-01-20 21:19:01

标签: javascript angular typescript

我想从一个对象创建一个画廊。

角度 - 打字稿

我有这个功能:

showGallery(index: number) {
    let prop = {
        images: [
            {path: 'https://web-service/attach/file/' + this.PIC[0].guid},
            {path: 'https://web-service/attach/file/' + this.PIC[1].guid},
            {path: 'https://web-service/attach/file/' + this.PIC[2].guid}
        ],
        index
    };
    this.gallery.load(prop);
}

而且我不知道如何在这个函数中创建循环。

我有一个带有图形 GUID 的 PIC 数组。 PIC 是通过 API 调用数据库创建的,当然图片数量总是不同的。

谁能解释一下,为什么我不能这样做:

showGallery(index: number) {
        let prop = {
            images: [
                for(var PICs of PIC){
                {path: 'https://web-service/attach/file/' + PICs.guid}
           }
            ],
            index
        };
        this.gallery.load(prop);
    }

这与范围界定有什么共同之处吗?

1 个答案:

答案 0 :(得分:1)

如果您需要遍历数组的每个元素,map 非常有用。它返回一个新的对象数组,由您传递给它的函数的返回值指定。在您的代码中,它看起来像这样:

showGallery(index: number) {
    let prop = {
        images: this.PIC.map(p => { path: 'https://web-service/attach/file/' + p.guid }),
        index
    };
    this.gallery.load(prop);
}