Javascript 有办法做到 "find_if" 或 "FirstOrDefault" 吗?
Does Javascript have a way of doing "find_if" or "FirstOrDefault"?
我是一名初级 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:
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++ 有一个 find_if
,这有点像我想要的。
因为你已经得到了映射,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 );
}
});
你在算法方面想太多了。而是从数据结构的角度思考:
if (arrowKeyMap[e.keyCode]) { // keymap exist?
SG.snake.changeDirection(arrowKeyMap[e.keyCode]);
}
您可以使用 JSLinq。它为 js 提供了与 c# 相同的 linq 函数。
我是一名初级 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:
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++ 有一个 find_if
,这有点像我想要的。
因为你已经得到了映射,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 );
}
});
你在算法方面想太多了。而是从数据结构的角度思考:
if (arrowKeyMap[e.keyCode]) { // keymap exist?
SG.snake.changeDirection(arrowKeyMap[e.keyCode]);
}
您可以使用 JSLinq。它为 js 提供了与 c# 相同的 linq 函数。