2011-11-21 88 views
2

我有一個JS函數,加載時調用一些變量,這一切運作良好,但是當我從另一個函數調用函數,我得到這個錯誤Cannot call method 'split' of undefined不能調用未定義的方法「拆分」 - 調用從函數

function loadInAttachmentsIntoSquads(){ 
    // eg: 5000,5000,5000,5000 > [5000][5000][5000] 
    myAttachmentArray = currentAttachments.split(','); 

    //eg: [5000][5000][5000] > [5][0][0][0] 
    //myAttachmentForWeapon = myAttachmentArray[mySquadsIndex].split(''); 

    setupWeaponAttachments(); 
} 


function setupWeaponAttachments(){ 

    myAttachmentForWeapon = myAttachmentArray[mySquadsIndex].split(''); 

    //if(mySquadsIndex == 0){ 
     if(myAttachmentForWeapon[1] == 1){ // if silencer is on? //first digit is always 5 
      weaponAttachments.silencer = true; 
     } 
     else{ 
      weaponAttachments.silencer = false; 
     } 
     if(myAttachmentForWeapon[2] == 1){ // if silencer is on? //first digit is always 5 
      weaponAttachments.grip = true; 
     } 
     else{ 
      weaponAttachments.grip = false; 
     } 
     if(myAttachmentForWeapon[3] == 1){ // if silencer is on? //first digit is always 5 
      weaponAttachments.redDot = true; 
     } 
     else{ 
      weaponAttachments.redDot = false; 
     } 

    // -- applies visuals -- \\ 
    applyWeaponAttachments(); 
} 

如果我打電話setupWeaponAttachments()從另一個函數,我得到這個錯誤...爲什麼?

+0

'mySquadsIndex'的價值是什麼? –

+0

它是一個動態值,範圍從0到4(有效) –

+0

它並不完全工作,因爲它被設置爲數組中沒有任何內容的索引。 –

回答

2

在下面:

> function loadInAttachmentsIntoSquads(){ 
>  
>  myAttachmentArray = currentAttachments.split(','); 
> 
>  setupWeaponAttachments(); 
> } 

標識符currentAttachments用作如果它是一個全局變量。如果它沒有被賦值,或者它的值不是一個字符串,那麼在調用該函數的時候,會導致錯誤。

所以解決方法是,以確保它有一個字符串值:

function loadInAttachmentsIntoSquads(){ 
    if (typeof currentAttachments != 'string') return; 
    ... 
} 

或處理錯誤一些其他的方式。

而且,當你正在做的所有這些的if..else塊,可以考慮:

weaponAttachments.silencer = myAttachmentForWeapon[1] == 1; 
weaponAttachments.grip  = myAttachmentForWeapon[2] == 1; 
weaponAttachments.redDot = myAttachmentForWeapon[3] == 1; 

這不會是任何更快,但它是少了很多代碼來寫和讀。

0

您誤解/誤用了JavaScript的範圍規則。

嘗試通過你明確和一貫分裂陣列,它應該解決您的問題,以及保持全局命名空間更簡潔:

首先,通過附件中明確你的第一個功能:

function loadInAttachmentsIntoSquads(currentAttachments) { 
    var myAttachmentArray = currentAttachments.split(','); 
    setupWeaponAttachments(myAttachmentArray); 
} 

請注意我上面做的幾件事情。首先,我將一個currentAttachments參數添加到函數中,而不是僅僅依賴先前聲明的全局變量。其次,我通過使用var關鍵字將myAttachmentArray聲明爲局部變量。聲明變量var將它們聲明在本地範圍內;否則會在全球範圍內宣佈它們。第三,我是手動的陣列傳遞到setupWeaponAttachments功能,這也是我將接受的說法:

function setupWeaponAttachments(myAttachmentArray) { 
    var myAttachmentForWeapon = myAttachmentArray[mySquadsIndex].split(''); 
    // [...] 
} 

請注意,我再次正確宣告myAttachmentForWeapon變量在局部範圍。

如果您在管理範圍和正確定義函數時要更加謹慎,以接收他們需要的參數並對其進行操作,您將來可以節省很多頭痛,並且您將會大大減少像這樣的問題。

相關問題