首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >为什么我的“for”循环函数不能工作?

为什么我的“for”循环函数不能工作?
EN

Stack Overflow用户
提问于 2014-05-01 16:12:35
回答 1查看 142关注 0票数 1

我正在用Javascript / jQuery创建一个带有我自己的定制步骤的滑块。

这里我使用的是一个for循环,但是我的函数只起作用,当我将一个while循环放入其中时。

work) First代码(没有while )

代码语言:javascript
运行
复制
var steps = '';

// Setting up the steps according to the number of slides
for( var i = 0; i < $itemsCount; ++i ) {

    var step = '';

    // Find step number and step text
    var step_text = $items.eq(i).attr('data-title');

    var step_count = i + 1;

    // current step will have the class 'current'
    var step = i === current ? '<li class="step current"><span data-step="'+ step_count +'">'+ step_text +'</span></li>' : '<li class="step"><span data-step="'+ step_count +'">'+ step_text +'</span></li>';

    i++;
    steps += step;
}

var navSteps = $( '<ul class="steps"/>' ).append(steps).prependTo($slider);

第二代码 (Did - with while )

代码语言:javascript
运行
复制
var steps = '';

// Setting up the steps according to the number of slides
for( var i = 0; i < $itemsCount; ++i ) {

    var step = '';

    // Find step number and step text
    while (i < $itemsCount) {

        var step_text = $items.eq(i).attr('data-title');

        var step_count = i + 1;

        // current step will have the class 'current'
        var step = i === current ? '<li class="step current"><span data-step="'+ step_count +'">'+ step_text +'</span></li>' : '<li class="step"><span data-step="'+ step_count +'">'+ step_text +'</span></li>';

        i++;
        steps += step;
    }
}

var navSteps = $( '<ul class="steps"/>' ).append(steps).prependTo($slider);

这并不是一个真正的问题,但我仍然不知道为什么第一个没有工作。

有人能告诉我为什么我要用while代替循环吗?

EN

Stack Overflow用户

回答已采纳

发布于 2014-05-01 16:14:39

在第一个例子中,您要增加两次"i“:一次在循环主体的末尾,一次在循环头中(圆括号中的i++ )。

添加while循环时,基本上会使for循环(大部分)变得无关紧要,因为当while循环退出时,"i“的值也会导致for循环退出。

票数 10
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/23411665

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档