简体   繁体   中英

Variable is undefined in function

I have a string with comma separated values:

var newVal = "9103174091,1231231232"
$(ctrl).val(DataReview.Encryption.formatPersonNmbr(newVal));

I call a function with this value:

function (val) {

        val = val.split(",");
        var newVal = "";
        for (var i = 0; i <= val.length; ++i)
        {
            val[i] = val[i].replace(/ /g, '');
            var newVal = val[i];

            if (val[i].length == 10 || val[i].length == 11 || val[i].length == 12) {
                if (val[i].length == 11) {
                    val[i] = val[i].substring(0, 6) + val[i].substring(7);
                }
                if (val[i].length == 10) {
                    var year = '20' + val[i].substring(0, 2);
                    var month = val[i].substring(2, 4);
                    var day = val[i].substring(4, 6);
                    var date = new Date(year, month - 1, day);

                    if (isNaN(date) == false) {
                        var currentDate = new Date();
                        if (date > currentDate) {
                            val[i] = '19' + val[i];
                        } else {
                            val[i] = '20' + val[i];
                        }
                    }
                }
            }

            newVal += val[i].substring(0, 8) + '-' + val[i].substring(8);   
        }

        return newVal;
    }

When I run this, I get the following error:

TypeError: val[i] is undefined
val[i] = val[i].replace(/ /g, '');

I can't understand how this can be undefined? What am I doing wrong?

Are you sure this is the correct end condition for your for loop?

for (var i = 0; i <= val.length; ++i)

Or did you mean this:

for (var i = 0; i < val.length; ++i)

This might be caused by 1-off errors. Accessing the element after the last element evaluates to undefined .

Example

var list = [2, 4, 6, 8];

for (var i = 0; i <= val.length; i++){
  console.log(list[i]);
}

Output

2
4
6
8
undefined

The last occurence is undefined because there is no value at val[4] , values in the list are accessible only up to val[3] . Its index reaches 4 because val.length returns 4, because there are four elements. Using the less than or equal operator to allows this error to occur.

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