【问题标题】:Issue with variable being undefined变量未定义的问题
【发布时间】:2015-03-07 22:30:00
【问题描述】:

我创建了一个循环遍历一组产品的函数,并将其复制区域的高度设置为该组中最高复制区域的高度。

这是我的代码:

function productCopyHeight(){
    //make sub range product text sections the same height
    if($('.sub-range').length){
        $('.sub-range').each(function(){
            var itemHeight = 0;
            $(this).children('.product-item').children('.copy').each(function(i){
                var thisItemHeight = $(this).height();
                console.log(thisItemHeight + ' > ' + itemHeight)

                if(thisItemHeight > itemHeight){
                    var itemHeight = thisItemHeight;
                }

            });
            $(this).children('.product-item').children('.copy').css('height', itemHeight);
        })
    }

}

当我记录它时,当它在每个循环之前定义时,它显示 itemHeight 变量为未定义。

【问题讨论】:

  • itemHeight 未定义在哪一行?
  • console.log 的输出是什么?
  • 控制台输出是'44 > undefined'

标签: jquery scope


【解决方案1】:

这是因为您在内部each 的回调中声明了另一个同名变量。这里:

if(thisItemHeight > itemHeight){
  var itemHeight = thisItemHeight;
}

该变量与循环之前的变量不同,并且该变量也被提升到函数的顶部。该变量的值为undefined,因为您在为其赋值之前使用了它。

您应该使用已有的变量,而不是创建另一个变量:

if(thisItemHeight > itemHeight){
  itemHeight = thisItemHeight;
}

【讨论】:

  • 谢谢你,很明显现在我有了答案,facepalm。虽然现在控制台正在输出 '22 > 0, 44 > 22, 44 > 0'
  • @Forxs:如果您在外循环中有两次迭代,那看起来是正确的。你期待什么结果?
  • 忽略这一点,这只是糟糕的逻辑 - 变量需要在前一个 .each 之前设置。感谢您的帮助
猜你喜欢
  • 2017-09-22
  • 2019-09-21
  • 2020-06-12
  • 1970-01-01
  • 2018-01-08
  • 2021-05-30
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
相关资源
最近更新 更多