Javascript 未捕获的类型错误:无法读取未定义的属性“substr”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26180018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught TypeError: Cannot read property 'substr' of undefined
提问by docwho
Pardon me for not being clear, but have thia script that is really long. When I have it live, I get this error in Chrome's Console.
请原谅我不清楚,但有很长的脚本。当我使用它时,我在 Chrome 的控制台中收到此错误。
Uncaught TypeError: Cannot read property 'substr' of undefined
未捕获的类型错误:无法读取未定义的属性“substr”
here is the snippet of code where it is reading from.
这是它正在读取的代码片段。
var formIddd = $('select[class~="FormField"]').get(numSelec).name.substr($('select[class~="FormField"]').get(numSelec).name.length-3,2);
I looked up substr on google and it appears to be a known property. I also found the classes. I have played with the lengths, but still getting stuck. It used to work until BigCommerce did an update.
我在谷歌上查找了 substr,它似乎是一个已知的属性。我也找到了课程。我玩过长度,但仍然卡住了。它过去一直有效,直到 BigCommerce 进行更新。
Any advice much appreciated, cheers.
非常感谢任何建议,干杯。
回答by epascarello
You are not populating your array. The if check is false.
您没有填充数组。if 检查是假的。


so basically you are doing this
所以基本上你正在这样做
var arrayOfSelectOfCountry = [];
var numSelec = arrayOfSelectOfCountry[-1]; //undefined
which results in the error above.
这导致上面的错误。
回答by Basheer AL-MOMANI
maybe at some point the substr()is called on a null reference
也许在某个时候substr()被称为null reference
so before using it check that reference for nullity like that
所以在使用它之前检查该引用是否为空
function(jsonDate) {
if (jsonDate!=null) {
//if the variable is not null you can use substr with no problems
var date = new Date(parseInt(jsonDate.substr(6)));
//.....
}
take look at my full snippet from Datatable
看看我的完整片段 Datatable
columns: [
{ 'data': 'ID' },
{ 'data': 'Name' },
{
'data': 'DateCreated',
'render': function(jsonDate) {
if (jsonDate!=null) {
var date = new Date(parseInt(jsonDate.substr(6)));
return date.toLocaleDateString();
}
return "-";
}
},

