2011-11-21 91 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变量在局部范围。

如果您在管理范围和正确定义函数时要更加谨慎,以接收他们需要的参数并对其进行操作,您将来可以节省很多头痛,并且您将会大大减少像这样的问题。

相关问题