无法调用undefined的方法'split' - 从函数调用

时间:2011-11-21 01:08:00

标签: javascript arrays variables split

我有一个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(),我会收到错误...为什么?

2 个答案:

答案 0 :(得分:3)

以下内容:

> 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;

它不会更快,但写入和读取的代码要少得多。

答案 1 :(得分:0)

您误解/滥用了JavaScript的范围规则。

尝试显式且一致地传递您正在拆分的数组,它应该解决您的问题,并保持全局命名空间不那么混乱:

首先,明确传递第一个函数中的附件:

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

注意我上面做的几件事。首先,我将currentAttachments 参数添加到函数中,而不仅仅依赖于先前声明的全局变量。其次,我使用myAttachmentArray关键字将var声明为局部变量。用var声明变量在本地范围内声明它们;没有这样做在全球范围内声明它们。第三,我手动将数组传递给setupWeaponAttachments函数,我将在其中收到参数:

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

请注意,我再次在本地范围内正确声明了myAttachmentForWeapon变量。

如果你更谨慎地管理范围并正确定义函数来接收他们需要的参数并对它们进行操作,那么你将来会为自己节省很多麻烦,并且你将会大大减少这些问题。< / p>