简体   繁体   中英

String variable prefixed with undefined in for loop

I have a drop-down on which i use .Change() to trigger a function. Function basically get certain data using getJSON and based on those value in have to create string of array for mp3 file.

Below code is generating string but always prefix undefined to string.

In code you will notice setTimeout which is just to provide certain delay till data received. In below example i am using static value and it still prefix undefined . not sure why may be i have defined variable in wrong manner.

Complete example JSBin

$('.customSurah').change(function(){
    //surahNo = $('#surah option:selected').val();

    setTimeout(function(){ 
    //countSpan = $('#surah-wrapper').children().length;
    surahNo = 1;
    countSpan = 7;
    var i=0;
         for (i = 0; i <= countSpan; i++) {
            strCat += surahNo+"/"+i+".mp3,";
            console.log(strCat);
        }
    }, 3000);

 });

OUTPUT

undefined114/0.mp3,
undefined114/0.mp3,114/1.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,
undefined114/0.mp3,114/1.mp3,114/2.mp3,114/3.mp3,114/4.mp3,114/5.mp3,114/6.mp3,

You have a variable strCat that is not initialized, and then you append a value to it in this line:

strCat += surahNo+"/"+i+".mp3,";

Since strCat is not initialized in first round of loop, you get undefined prepended to your string.

To fix this, you need to initialize the variable to empty value first:

var strCat = '';   // <- initialize your variable to empty value
surahNo = 1;
countSpan = 7;

The outcome is perfectly valid as per javascript is concerned.

Why?

I guess you probably know if you declare any variable in javascript and you don't assign its default value then automatically undefined is assigned. So, that is a valid. What happens when you do that:

 var somevar; // non assigned default value set to -> undefined console.log(somevar); // logs undefined 

But,
In your case you have to give it a default value like a blank string var strCat ""; . So, now when you do this:

 var somevar = ""; // assigned default value to set to -> "" console.log(somevar); // logs "" 


So, the solution to your issue is, you have to initialize/assign a default value to your variable. like:

var strCat = "";

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM