[英]In Javascript, is there an equivalent of a “find if”, or a compact way of doing what I'm trying to do?
I have an ugly piece of Javascript code 我有一段难看的Javascript代码
for (var k = 0; k < ogmap.length; ++k)
{
if (ogmap[k]["orgname"] == curSelectedOrg)
{
ogmap[k]["catnames"].push(newCatName);
break;
}
}
Actually, I have a lot of pieces like that in my web app. 实际上,我的Web应用程序中有很多类似的内容。
I'm wondering if there's a way to make it prettier and compacter. 我想知道是否有办法使它更漂亮,更紧凑。 I know there are nice ways of doing this in other languages, like using find_if
in C++ ( http://www.cplusplus.com/reference/algorithm/find_if/ ) or FirstOrDefault
in C# or fancy LINQ queries in C#. 我知道有其他语言这样做的很好的途径,如使用find_if
在C ++( http://www.cplusplus.com/reference/algorithm/find_if/ )或FirstOrDefault
在C#或花哨LINQ查询在C#。
At the very least, help me make that slightly more readable. 至少,请帮助我使它更具可读性。
I'd say that you can just write yourself a utility function and then use it whenever necessary. 我想说的是,您可以编写一个实用程序函数,然后在必要时使用它。
// finds the first object in the array that has the desired property
// with a value that matches the passed in val
// returns the index in the array of the match
// or returns -1 if no match found
function findPropMatch(array, propName, val) {
var item;
for (var i = 0; i < array.length; i++) {
item = array[i];
if (typeof item === "object" && item[propName] === val) {
return i;
}
}
return -1;
}
And, then you can use it like this: 然后,您可以像这样使用它:
var match = findPropMatch(ogmap, "orgname", curSelectedOrg);
if (match !== -1) {
ogmap[match]["catnames"].push(newCatName);
}
var find_if = function (arr, pred) {
var i = -1;
arr.some(function (item, ind) {
if (pred(item)) {
i = ind;
return true;
}
});
return i;
}
Call it like 像这样称呼它
var item_or_last = find_if(_.range(ogmap.length), function (item) {
return item["orgname"] == curSelectedOrg
});
Or without underscore.js 还是没有underscore.js
var range = function (a, b) {
var low = a < b ? a : b;
var high = a > b ? a : b;
var ret = [];
while (low < high) {
ret.push(low++);
}
return ret;
}
var item_or_last = find_if(range(0, ogmap.length), function (item) {
return item["orgname"] == curSelectedOrg
});
This lets you declare what you are looking for instead of looping over items and checking each one. 这使您可以声明要查找的内容,而不必遍历项目并检查每一项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.