【问题标题】:Uncaught TypeError: Cannot read property 'substr' of undefined未捕获的类型错误:无法读取未定义的属性“substr”
【发布时间】:2014-11-28 13:48:20
【问题描述】:

请原谅我没有说清楚,但是这个脚本真的很长。当我启用它时,我在 Chrome 的控制台中收到此错误。

未捕获的类型错误:无法读取未定义的属性“substr”

这里是读取的代码的 sn-p。

var formIddd = $('select[class~="FormField"]').get(numSelec).name.substr($('select[class~="FormField"]').get(numSelec).name.length-3,2);

我在 google 上查找了 substr,它似乎是一个已知属性。我也找到了课程。我玩过长度,但仍然卡住了。在 BigCommerce 进行更新之前,它一直有效。

非常感谢任何建议,干杯。

【问题讨论】:

  • 仔细阅读错误。 “无法读取未定义的属性 'substr'”。这意味着 name 未定义,而不是 substr
  • 调试:var elems = $('select[class~="FormField"]'); console.log(numSelec, elems.length, elems.get(numSelec));
  • @AmitJoki 如果索引超出范围,则意味着get(numSelec) would be undefined, which would result in the error Cannot read property 'name' of undefined. So get(numSelec)` 的结果会返回一些东西,但它没有name 属性。
  • 还有你的问题:numSelecundefined
  • 您需要显示更多代码,执行顺序有问题。

标签: javascript jquery bigcommerce


【解决方案1】:

你没有填充你的数组。 if 检查为假。

所以基本上你正在这样做

var arrayOfSelectOfCountry = [];
var numSelec = arrayOfSelectOfCountry[-1];  //undefined

导致上述错误。

【讨论】:

    【解决方案2】:

    也许在某个时候substr() 会在 null reference 上被调用

    所以在使用它之前检查该引用是否为空值

    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)));
            //.....
    }
    

    看看我来自Datatable的完整sn-p

     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 "-";
                                }
                            },
    

    【讨论】:

      【解决方案3】:

      代替:

      variable.substring(0, 7)
      

      做:

      variable && variable.substring(0, 7)
      

      这就是像 Basheer 提到的那样检查无效性的方式

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-12-26
        • 2015-01-20
        • 2021-12-22
        • 2015-01-06
        • 2017-07-26
        • 2019-02-26
        相关资源
        最近更新 更多