Coffeescript - 嵌套循环

时间:2014-05-24 16:06:42

标签: jquery coffeescript

我想迭代两个数组并检查第二个数组是否有任何与第一个数组匹配的值。我目前正在尝试如下,但我确定它不正确。我该怎么办?

changeType = (el,shapeType) ->
 elTypes = ['circle','square','triangle']
 elClasses = el.attr 'class'
 classTypes = elClasses.split " " 

  for type of elTypes
    for types of classTypes
    el.removeClass type  if classTypes[types] is elTypes[type] 
 el.addClass shapeType

[编辑] ,而结构似乎也不正确

 x = 0
 while x <= classTypes.length
   i = 0
   while i <= elTypes.length
     if elTypes[i] is classTypes[x]
        el.removeClass elTypes[i]
   i++
  x++
  el.addClass type

3 个答案:

答案 0 :(得分:1)

这应该有效

changeType = (el,shapeType) ->
    elTypes = ['circle','square','triangle']
    elClasses = el.attr 'class'
    classTypes = elClasses.split " " 

    for type of elTypes
        for types of classTypes
            if types == type then el.removeClass type 
     el.addClass shapeType

答案 1 :(得分:0)

你的缩进是错误的:

for type of elTypes
  for types of classTypes
  el.removeClass type  if classTypes[types] is elTypes[type]

应该缩进el.removeClass以使其进入for types循环。

但这一切都是毫无意义的繁忙工作。 removeClass可以自行删除多个类:

  

可以一次删除多个类,用空格分隔,匹配元素集合,如下所示:

$( "p" ).removeClass( "myClass yourClass" )

不要打扰循环,让jQuery处理它:

changeType = (el, shapeType) ->
  el.removeClass('circle square triangle').addClass(shapeType)

我认为这就是你真正追求的目标。


我还注意到你似乎在CoffeeScript中混合了一个空格和两个空格的缩进。这不是你曾经拥有过的最好的主意。选择缩进量并在CoffeeScript中一致地使用它:缩进定义了CoffeeScript的结构,因此必须非常小心。

答案 2 :(得分:0)

好的,这是一个小错误。这当然有效:

 for types of classTypes
        for type of elTypes
            if classTypes[types] == elTypes[type] then el.removeClass elTypes[type] 
     el.addClass shapeClass
相关问题