javascript 返回一项的 jQuery Grep 替代方案

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18018186/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 10:29:06  来源:igfitidea点击:

jQuery Grep Alternatives to Return One Item

javascriptjquery

提问by Jammer

I'm looking at some jQuery code I'm writing at the moment and it just looks plain weird to my C# brain. Is there a better way of doing this?

我正在查看我目前正在编写的一些 jQuery 代码,它在我的 C# 大脑中看起来很奇怪。有没有更好的方法来做到这一点?

var idToLookFor = 2;
var myArray = [{id:1},{id:2},{id:3}]

var arrayItem = $.grep(myArray , function (elm) {
    return elm.id == idToLookFor;
});

var itemFound = arrayItem[0];

I can understand grep returning an array as rather than it being a find type function its a filter type function so I guess the question should really be is there a function that will only return one item rather than an array?

我可以理解 grep 返回一个数组,而不是它是一个查找类型函数,它是一个过滤器类型函数,所以我想问题真的应该是是否有一个函数只返回一个项目而不是一个数组?

采纳答案by lewis

This answer to another question points out that grep will continue looping over the array even after it has found the right answer. Not an issue in the above example but if your array could be much larger it's worth noting: non grep solution

这个对另一个问题的回答指出,即使在找到正确答案之后,grep 仍将继续循环遍历数组。在上面的示例中不是问题,但如果您的数组可能更大,则值得注意:非 grep 解决方案

It's just a for loop that is wrapped in a function that returns the object it finds. Even if you stick with the grep method I'd still abstract your logic into some reusable function and keep it in a nice helper file somewhere.

它只是一个包装在一个函数中的 for 循环,该函数返回它找到的对象。即使您坚持使用 grep 方法,我仍然会将您的逻辑抽象为一些可重用的函数,并将其保存在某个不错的帮助文件中。

I'm posting a modified version of the answer purely so you can see what I mean before deciding if you want to follow the link:

我纯粹是发布答案的修改版本,以便您在决定是否要点击链接之前了解我的意思:

for (var i = 0, len = myArray.length; i < len; i++) 
{
    if (myArray[i].id === idToLookFor)
    {
        return myArray[i]; // Return as soon as the object is found
    }
}

回答by José Andias

Well, if you like using jQuery generic function style, you could add something like this in your personal library:

好吧,如果你喜欢使用 jQuery 通用函数风格,你可以在你的个人库中添加这样的东西:

$.extend( {
    findFirst: function( elems, validateCb ){
        var i;
        for( i=0 ; i < elems.length ; ++i ) {
            if( validateCb( elems[i], i ) )
                return elems[i];
        }
        return undefined;
    }
} );

Usage for your example:

您的示例的用法:

var result = $.findFirst( myArray, function(elm) {
    return elm.id == idToLookFor;
});

Of course, you could instead use your own namespace...

当然,您可以改为使用自己的命名空间...

I assume your concern is with code readability. I think using directly a language loop solution for this matter is also quite fine.

我认为您关心的是代码可读性。我认为直接使用语言循环解决方案来解决这个问题也很好。

You could also be concerned with waste, as there is no need to maintain another array structure just for this, but at least for your example it seems like a micro-optimisationissue.

您也可能会担心浪费,因为没有必要为此维护另一个数组结构,但至少对于您的示例而言,这似乎是一个微优化问题。

回答by underbar

Expanding on Blazemonger's comment:

扩展 Blazemonger 的评论:

var itemFound = myArray[idToLookFor - 1]

should get you the item you're looking for if I understand your question correctly. Note the -1 to account for indexing from 1

如果我正确理解您的问题,应该会为您提供您正在寻找的项目。注意 -1 以说明从 1 开始索引

EDIT: this also assumes that the array will always be sorted in ascending order by ID as it is in your question. If your id's do increment nicely but the array is not initially sorted by them see: Sort array of objects by string property value in JavaScript

编辑:这也假设数组将始终按 ID 升序排序,就像在您的问题中一样。如果您的 id 增加得很好,但数组最初并未按它们排序,请参阅:在 JavaScript 中按字符串属性值对对象数组进行排序

回答by Aditya

If you have an array of Objects, this would do:

如果您有一组对象,则可以这样做:

var result = myArray.filter(function(v) {
    return v.id === idToLookFor; 
})[0];

For a simple array You could use inArray.It returns the key of the array where the item is present!.

对于一个简单的数组,您可以使用inArray 。它返回该项目所在数组的键!。

var itemFound= myArray[$.inArray(idToLookFor,myArray)];

var itemFound= myArray[$.inArray(idToLookFor,myArray)];

回答by nalin

Please use

请用

var idToLookFor = 2;
var myArray = [{id:1},{id:2},{id:3}]

var arrayItem = $.map(myArray , function (elm) {
    if(elm.id == idToLookFor)
      return elm.id ;
});

var itemFound = arrayItem[0];

回答by Abou-Emish

check my answer here

在这里检查我的答案

Copied from polyfill Array.prototype.find code of Array.find, and added the array as first parameter.

复制自 Array.find 的 polyfill Array.prototype.find 代码,并添加数组作为第一个参数。

you can pass the search term as predicate function

您可以将搜索词作为谓词函数传递