2012-11-08 172 views
1

我创建了一个基于网格文字替代解决方案underscore.js

在我的代码正在填充我有underscore.js一个小一点,可以帮助我的话适合在可用空间游戏电网没有突破电网障碍。

据我所知,它是非常强大的Java脚本,并不亲自有一个问题。但是我的团队经理希望摆脱它,因为只有一个函数可以提供相同的解决方案,并且可以节省我拥有整个库的jQuery。我将如何用一些jQuery替换这个?

function getWordToFitIn(spaceAvail, wordlist) { 
    var foundIndex = -1; 
    var answer = _.find(wordlist, function (word, index) { 
     if (word.length <= spaceAvail) { 
      foundIndex = index; 
      return true; 
     } 
    }); 
    if (foundIndex == -1) { 
     answer = getXSpaces(spaceAvail); 
     _.find(wordlist, function (word, index) { 
      if (word[0] == " ") { 
       foundIndex = index; 
       return true; 
      } 
     }); 
    } 
    if (foundIndex != -1) { 
     wordlist.splice(foundIndex, 1); 
    } 
    return answer; 
} 
+5

研究源码。 http://underscorejs.org/docs/underscore.html –

+0

我看了一下。我明白它在做什么,我只是不知道如何去取代它。 @ user1689607 –

+1

哪部分你不明白? *(看起来好像我过去和你有过这样的对话)。* –

回答

2

据我所见,您唯一使用的下划线方法是_.find。但我认为你没有按照它的意图使用它。看起来你只是简单循环,并在符合条件时返回true。

如果您没有旧式支持或使用垫片,则可以使用本机forEach。或者您可以使用jQuery.each方法。

第一循环可以可能(我不是100%肯定的answer变量)这样写:

var answer; 
$.each(wordlist, function(index, word) { 
    if (word.length <= spaceAvail) { 
     foundIndex = index; 
     answer = word; 
     return false; // stops the loop 
    } 
}); 

,第二个:

$.each(wordlist, function (index, word) { 
    if (word[0] == " ") { 
     foundIndex = index; 
     return false; 
    } 
}); 
+0

谢谢。最后一点呢?它保持不变吗? @David –

+0

@ Milo-J最后一点?就我所见,剩下的就是原生JavaScript。 – David

+0

@ Milo-J:也许你应该尝试一下并找出答案。 –