2011-11-04 91 views
1

我創建了另一篇文章,但我沒有完全寫出正確的代碼以及問題是什麼。 所以在這裏完整的代碼。 我在create函數中聲明瞭「myarray」。我將成功函數中的值推送到數組,並返回到create create函數中。返回全局數組,其值設置在函數中

問題是我在調用create函數時沒有返回任何值。我認爲這是我的陣列的範圍,但我不知道如何解決這個問題。

function Create(targetdir) 
    { 
     var myarray = new Array(); 

     //Get a list of file names in the directory 
     window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError); 

     function onSuccess(fileSystem) 
     { 
      var entry=fileSystem.root;  
      entry.getDirectory(targetdir, {create: false, exclusive: false}, successdir, fail);  

      //filesystem2 is the target dir 
      function successdir(fileSystem2) 
      {   
       var directoryReader = fileSystem2.createReader(); 
       directoryReader.readEntries(success, fail); 

       function success(entries) 
       { 

        var i; 
        for (i=0; i<entries.length; i++) 
        { 
         myarray.push(entries[i].toURI()); 
        }   
       } 
      }   
     } 

     return myarray; 
    } 

回答

1

使用的回調:

function Create(targetdir, callback) 
{ 
    var myarray = new Array(); 

    //Get a list of file names in the directory 
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError); 

    function onSuccess(fileSystem) 
    { 
     var entry=fileSystem.root;  
     entry.getDirectory(targetdir, {create: false, exclusive: false}, successdir, fail);  

     //filesystem2 is the target dir 
     function successdir(fileSystem2) 
     {   
      var directoryReader = fileSystem2.createReader(); 
      directoryReader.readEntries(success, fail); 

      function success(entries) 
      { 

       var i; 
       for (i=0; i<entries.length; i++) 
       { 
        myarray.push(entries[i].toURI()); 
       }   
      } 
     } 

     // call callbqack 
     callback(myarray);  
    } 
} 

然後:

Create(whatever, function (myarray) { 
    // do something with my array 
}); 
+0

指定我得到這個錯誤使用回調方法: 的ReferenceError:找不到變量:回調 – michael643

+0

回調是創建第二個參數。 –

0

因爲你調用一個異步方法你創建方法alwasy將返回任何結果,因爲window.requestFileSystem仍做他的工作。你可以做以下

function Create(targetdir) 
{ 
    window.requestFileSystem(LocalFileSystem.PERSISTENT, 0, onSuccess, onError); 

    function onSuccess(fileSystem) 
    { 
     var myarray = new Array(); 
    // fill myarray 
    // use myarray or skip the fill array and use it directly 
    } 
} 

或由@IAbstractDownvoteFactor

+0

謝謝你的回覆,但是我不會在這個例子中返回數組,以便在腳本中使用它。 – michael643

+0

對不起,我沒有看到第二個參數。 – michael643