数组查找,本机或通过jQuery? [英] Array find, natively or through jQuery?

查看:55
本文介绍了数组查找,本机或通过jQuery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你会做这类事吗?

    var getBoard1 = function(id) {
        return $.grep(me.boards, function (board) {
            return board.Id == id;
        });
    };

还是这类东西?

    var getBoard2 = function(id) {
        for (var i = 0; i < me.boards.length; i++) {
            var board = me.boards[i];
            if (board.Id == id)
                return board;
        }
        return null;
    };

为什么在正确性,可读性和性能方面你更喜欢这种方式?如果您希望以第三种方式进行,请分享。

And why, in the context of correctness, readability and performance would you prefer that way? If you would rather do it in a third way, please share.

推荐答案

这就是 grep 函数看起来像(jQuery v1.8.2):

This is what the grep function looks like (jQuery v1.8.2):

grep: function( elems, callback, inv ) {
    var retVal,
        ret = [],
        i = 0,
        length = elems.length;
    inv = !!inv;

    // Go through the array, only saving the items
    // that pass the validator function
    for ( ; i < length; i++ ) {
        retVal = !!callback( elems[ i ], i );
        if ( inv !== retVal ) {
            ret.push( elems[ i ] );
        }
    }

    return ret;
}

基本上,你也是这样做所以它不会太多性能方面的差异。当我查看jQuery代码时,它们总是返回一个数组,返回 null 。如果您已经使用了jQuery,我会选择jQuery版本,因为它更易读,否则请使用 native 代码。

Essentially, you're doing the same so it wouldn't be much of a difference when it comes to performance. When I look at the jQuery code, they always return an array, where you return null. If you're using jQuery already, I would go for the jQuery version since it's better readable, otherwise go with native code.

* - 编辑 - *

在查看代码时,这让我意识到 会有所作为。当代码找到第一个项目(只需要一个结果)时,你的代码已经返回(并完成循环),其中jQuery循环遍历 all 项目。因此,如果您只期望一个结果,那么您的版本会更快。

When looking at the code, this made me realize it does make a difference. Your code already returns (and finishes the loop) when it found the first item (expecting only one single result), where jQuery loops through all the items. So, if you expect only one result, your version would be faster.

这篇关于数组查找,本机或通过jQuery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆