[英]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 循环的正确结束条件吗?
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.这可能是由 1-off 错误引起的。 Accessing the element after the last element evaluates to undefined
.在最后一个元素评估为undefined
之后访问该元素。
var list = [2, 4, 6, 8];
for (var i = 0; i <= val.length; i++){
console.log(list[i]);
}
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]
.最后一次出现undefined
因为val[4]
没有值,列表中的值只能访问val[3]
。 Its index reaches 4 because val.length
returns 4, because there are four elements.它的索引达到 4,因为val.length
返回 4,因为有四个元素。 Using the less than or equal operator to allows this error to occur.使用小于或等于运算符允许发生此错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.