javascript - 在 for 循环中输出 javascript 数组值会导致未定义

标签 javascript jquery for-loop undefined

我正在尝试使用循环来输出 jQuery悬停函数上两个数组的值。在悬停之外,我可以很好地访问这些数组值,但在内部我无法定义。

JavaScript 对我来说还是个新手,所以请告诉我我的菜鸟错误。谢谢。

jQuery(document).ready(function($){
var originalWheelContent = $('.wheel-content').html(),
    transitionSpeed = 400,
    segmentTitle = ['collaborative','compassionate','inclusive','empowering','responsive'],
    segmentParagraph = [
        'Working together to deliver the best possible outcomes and recognises and values the contribution of others.',
        'Constantly looking for new ways to satisfy the needs of those you work with or care for. Acting with consideration and understanding for others feelings.',
        'Actively seeking and creating opportunities to include others, fostering an environment where everyone feels valued and respected.',
        'Enabling positive change and supporting others to reach their maximum potential.',
        'Reacting positively to change and others needs by being creative and innovative in finding solutions.'
    ];

for(x = 0; x < segmentTitle.length; x++){
    $('.wheel-graphic map area#' + segmentTitle[x]).hover(
        function(){
            $('.wheel-content').fadeOut(transitionSpeed,function(){
                $('.wheel-content').replaceWith('<div class="wheel-content"><h2 class="segment-title">' + segmentTitle[x] + '</h2><h4 class="segment-p">' + segmentParagraph[x] + '</h4></div>');
            });
        }, function() {
            $('.wheel-content').fadeIn(transitionSpeed);
            $('.wheel-content').replaceWith('<div class="wheel-content">' + originalWheelContent + '</div>');
        }
    );
   }
});

enter image description here

最佳答案

为了避免未定义,您需要确保循环递增变量x的作用域正确。

使用let:

for (let x = 0; x < segmentTitle.length; x++)

关于javascript - 在 for 循环中输出 javascript 数组值会导致未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50347022/

相关文章:

c - OpenMP 关于 for 循环

c++ - 在 C++ 中使用二维数组进行循环

javascript - 如何在 Angular Material 中制作所需的下拉列表?

javascript - JS(jQuery): Randomly trigger-click 2 table rows

jquery - 无法根据 JSON 数据中的决策值更改背景颜色

javascript - 与浏览器控制台相比,为什么相同的 jQuery 选择器在 React Component hooks 中具有不同的输出?

javascript - jquery 在 jQuery.noConflict() 之后重写;

javascript - IE6 : Background-Image Load Event

javascript - 如何在不使用表格的情况下设计两列表单布局

c - 在 C 中使用不同的数值为相同的操作获取不同的长度