从回调函数中访问外部数据。

时间:2021-10-02 23:44:40

I am having problems accessing nodes[i] from the callback function inside chrome.bookmarks.create. Any idea guys ? I am thinking this is because of closure. Any way to make it work ?

我在从chrome.bookmark .create内部的回调函数访问节点[I]时遇到了问题。知道男人吗?我想这是因为结束。有什么办法吗?

function copyBookmarks(nodes,folderId){            

    for(i=0;i<nodes.length;i++){

        var properties={
            parentId:folderId,
            index:nodes[i].index,
            title:nodes[i].title,
            url:nodes[i].url
        };   

        chrome.bookmarks.create(properties,function(newNode){              

          console.log(nodes[i]);//this doesnt work

        });                    
    }
}

1 个解决方案

#1


3  

It is accessing nodes just fine, but the problem is that i will be the value after the loop completes. The usual solution is to make a copy of i in each iteration through a self-executing function:

它可以很好地访问节点,但问题是循环完成后,i将是值。通常的解决方案是通过自执行函数在每次迭代中复制i:

for (var i = 0; i < nodes.length; i++) {

    // Other code...

    // Self executing function to copy i as a local argument
    (function (i) {
        chrome.bookmarks.create(properties, function (newNode) {
            console.log(nodes[i]);
        });
    })(i);
}

#1


3  

It is accessing nodes just fine, but the problem is that i will be the value after the loop completes. The usual solution is to make a copy of i in each iteration through a self-executing function:

它可以很好地访问节点,但问题是循环完成后,i将是值。通常的解决方案是通过自执行函数在每次迭代中复制i:

for (var i = 0; i < nodes.length; i++) {

    // Other code...

    // Self executing function to copy i as a local argument
    (function (i) {
        chrome.bookmarks.create(properties, function (newNode) {
            console.log(nodes[i]);
        });
    })(i);
}