Cannot call method 'split' of undefined - Called From Function

15,649

In the following:

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

The identifier currentAttachments is used as if it's a global variable. If it hasn't been assigned value, or its value isn't a string, at the time that the function is called, then an error will result.

So the fix is to make sure it has a string value:

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

or deal with the error some other way.

Also, where you are doing all those if..else blocks, consider:

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

It won't be any faster, but it is a lot less code to write and read.

Share:
15,649
Oliver Jones
Author by

Oliver Jones

Updated on June 17, 2022

Comments

  • Oliver Jones
    Oliver Jones almost 2 years

    I have a JS function that is called on load that spilts some variables, this all works well, but when I call the function from another function, I get this error 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();
    }
    

    If I call setupWeaponAttachments() from another function, I get that error ... why?