JavaScript is incorrectly trying to read path as a number - outputs NaN

42 views Asked by At

I'm using a hover function in Utilities namespace to return translated English word on mouseover:

hoverText : function () {
    $("#npc_dialog").lettering('words'); //split dialog into spans for hover

    //Provide translation on hover for Player Dialog
    $("#npc_dialog span").on("mouseover", function() {
        var word = $(this).text();
        $("#currentWord").text(Vocab.parseHoveredText(word, false));
        playSound(Vocab.parseHoveredText(word, true));
    })
}

This calls Vocab.parseHoveredText() to loop through vocab object and return either the translated word, or an audio path which will sound out the word.

Originally I had this.path+this.sbj+file.mp3 if I need to dynamically change paths later. The sound plays when I manually type the path in (in the case of 'wo'), but if I use the this.path+... console outputs NaNNi_You.mp3. Why is it trying to read it as a number when the path is NOT a number?

I've already verified the this.path and this.sbj paths are working in the console.log below.

//namespace
var Vocab = {

path : 'recordings/',
sbj : 'subjects/',
//more stuff

vocab : 
    {
        Subjects :
        {   
            'wǒ'    : ['I/Me',              'recordings/subjects/Wo_I.mp3'],
            'nǐ'    : ['You',               this.path+this.sbj+'Ni_You.mp3'],
            //more stuff

My parseHoveredText function:

parseHoveredText : function (word, audio) {
        for (obj in this.vocab) {
            if(this.vocab[obj][word.toLowerCase()]) { 
                if(audio) {
                    //Hover over 'wǒ': outputs: "path: recordings/subjects/Wo_I.mp3"
                    console.log("path: " + this.path+this.sbj+'Wo_I.mp3');

                    //Hover over 'wǒ': outputs: "log: recordings/subjects/Wo_I.mp3"
                    //Hover over 'nǐ': outputs: "log: NaNNi_You.mp3"
                    console.log("log: " + this.vocab[obj][word.toLowerCase()][1]);
                    return this.vocab[obj][word.toLowerCase()][1];

                }
                return this.vocab[obj][word.toLowerCase()][0];
            }
        }
    },
1

There are 1 answers

4
Stephen Thomas On

Since you haven't shown the entire code, it's not possible to say precisely, but when Vocab is defined, it is in some scope, possibly/probably the global scope. In any case, this is equal to that scope. So when your code says this.path+this.sbj JavaScript expects to find path and sbj in that scope, not as properties of the object. Since they aren't defined in that scope, undefined + undefined is NaN.