我需要从回调函数中获取参数“i”并将其移至“obj”。我读了很多相同的主题,但我仍然不明白它是如何工作的。请有人帮忙。
function getData(index,callback)
{
var openReq = indexedDB.open("catalogs");
openReq.onsuccess = function()
{
var db = openReq.result;
var transaction = db.transaction(['plants'], "readwrite");
var objectStore = transaction.objectStore("plants");
var objectStoreRequest = objectStore.get(index);
var store=null;
objectStoreRequest.onsuccess =function(event)
{
store =objectStoreRequest.result;
//console.log(store);
return store;
}
transaction.oncomplete = function(event)
{
db.close();
if(callback)
callback(store);
}
}
}
......一些代码......
for (var i = 101; i < 272; i++){
var obj= new Object();
getData(''+i,function (i){document.obj=i;});
console.log(obj);
}
答案 0 :(得分:0)
...您想要哪个值,来自for循环的i
还是来自回调的i
?他们有两个不同的价值观。
(我认为你想要的那个)
for (var i = 101; i < 272; i++){
var obj = {}; // same as `new Object()`
getData( i.toString(), function (result){
obj.yourPropertyNameHere = result;
console.log(obj);
});
}
for (var i = 101; i < 272; i++){
// we have to store a copy of the variable `i` in the closure
// of a function, otherwise all of the callbacks will reference
// the final value of `i` from the loop
(function(i_copy){
var obj = {}; // same as `new Object()`
getData( i_copy.toString(), function (result){
obj.yourPropertyNameHere = i_copy;
console.log(obj);
});
})(i);
}