Javascript 一种js循环结构的算法设计

Javascript 一种js循环结构的算法设计,javascript,Javascript,我得到了一个数组[1,2,3,4] 我需要先检查[2]被选中的孩子,设置他的风格,然后检查其他孩子,重新设置他们的风格 目前,我的算法如下所示: for item in array if item == chosenEl set chosen classes for item in array if item != chosenEl reset chosen classes for the rest of the children 或咖啡: f

我得到了一个数组
[1,2,3,4]

我需要先检查[2]被选中的孩子,设置他的风格,然后检查其他孩子,重新设置他们的风格

目前,我的算法如下所示:

for item in array
    if item == chosenEl
        set chosen classes
for item in array
    if item != chosenEl
        reset chosen classes for the rest of the children 
咖啡

for item in @array
    if item.element is element
        item.selected = true
        item.element.classList.add @selectedClass
        item.element.focus()
for item in @array
    if item.element isnt element
        item.selected = false
        item.element.classList.remove @selectedClass
由于me框架中的一些限制,我需要这样设计函数,而不是作为一个简单的forElse循环

如何改进此代码

多谢各位

解释-我之所以需要这种设计,是因为对两个不同函数的重复调用相互冲突

我正在为LG电视开发一个应用程序。LG电视有自己的图书馆。现在,我在函数中设置所选元素的样式。Byt当我聚焦到所选元素时,我会激活LG TV onFocus listener,它反过来控制所选的样式

因此,当我循环第二或第三个子元素时,我会再次设置已清除元素的选定样式。TLDR但这就是循环之间的冲突。一个打断另一个的工作


代码不是我写的。我输入了一个现有的项目,但是我还没有编写这个函数,所以我不能删除Focus()函数

为什么要循环两次?简单得多:

for( var i=0, l=array.length; i<l; i++) {
    if( item == chosenEl) {
        // set styles
    }
    else {
        // clear styles
    }
}

for(var i=0,l=array.length;i为什么循环两次?简单得多:

for( var i=0, l=array.length; i<l; i++) {
    if( item == chosenEl) {
        // set styles
    }
    else {
        // clear styles
    }
}

<代码> >(var i=0,L=alay.长度;i而不是循环两次,请考虑下面的代码

for item in array
{
    if item == chosenEl
    {
        set chosen classes
        continue; <--use this to return to next iteration without executing next statements
    } 
   reset chosen classes for the rest of the children
}
数组中项目的

{
如果项==chosenEl
{
设置选定的类

继续,而不是循环两次,考虑下面的代码

for item in array
{
    if item == chosenEl
    {
        set chosen classes
        continue; <--use this to return to next iteration without executing next statements
    } 
   reset chosen classes for the rest of the children
}
数组中项目的

{
如果项==chosenEl
{
设置选定的类

继续;您好@Kolink。谢谢您的评论,但正如我在OP中解释的,由于我的FW的限制,我无法运行简单的ForElse。我将在楼上解释我的限制是什么,这要求我考虑这个设计。您好@Kolink。谢谢您的评论,但正如我在OP中解释的,由于限制,我无法运行简单的ForElse我会在楼上解释我的限制是什么,这要求我考虑这个设计。嗨@Sundeep。谢谢你的评论,但正如我在OP中解释的,我不能运行一个简单的ForElse,因为我的FW的限制。我会在楼上解释我的限制是什么,这要求我考虑这个设计。嗨@Sundeep。谢谢谢谢你的评论,但正如我在OP中解释的,由于我的FW的限制,我不能运行一个简单的ForElse。我将在楼上解释我的限制是什么,这要求我考虑这个设计。