Javascript是否有办法做到" find_if"或" FirstOrDefault"?

时间:2015-08-05 06:26:11

标签: javascript jquery algorithm design-patterns

我是一名初级JavaScript开发人员,我发现我经常遇到需要做相同事情的情况

"Find the first element satisfying a condition, then do something with the element" 

我最终用for语句编写break循环。例如,这是我写的一段生产代码:

// set up event listeners for changing the snake's direction
// based on arrows keys pressed
// see: http://stackoverflow.com/questions/6226859/how-can-i-track-arrow-keys-in-chrome-and-ie
var arrowKeyMap = { 37 : "left", 38: "down", 39: "right", 40: "up" };
$(document).keydown(function (e)
{
    // want to make this more compact ...
    for (var i in arrowKeyMap)
    {
        if (i == e.keyCode)
        {
            SG.snake.changeDirection(arrowKeyMap[i]);  
            break;
        }
    }

});

我想知道是否有原生的JavaScript工具,或使用JQuery的方式,使其更紧凑,或者如果我需要手动滚动可重复使用的过程来处理这种情况。我知道C#有FirstOrDefault和C ++ a find_if,它们有点像我想要的。

3 个答案:

答案 0 :(得分:6)

由于您已经获得了映射,因此javascript Object允许您通过key直接查找,只需检查key的对象是否存在。

因此,您可以使用e.keyCode作为关键字来查找是否有映射。

var arrowKeyMap = { 37 : "left", 38: "down", 39: "right", 40: "up" };
$(document).keydown(function (e)
{
    var key = arrowKeyMap[e.keyCode];
    if (key) { // Do something if there's a map to the key.
       SG.snake.changeDirection(key );  
    }
});

答案 1 :(得分:2)

你在算法方面考虑得太多了。相反,请考虑数据结构:

if (arrowKeyMap[e.keyCode]) { // keymap exist?
    SG.snake.changeDirection(arrowKeyMap[e.keyCode]);
}

答案 2 :(得分:0)

您可以使用JSLinq。它为c#提供了相同的linq函数。