【问题标题】:ECMA5 array methods - Finding the first object of a kind in an arrayECMA5 数组方法 - 在数组中查找第一个对象
【发布时间】:2013-09-12 19:53:47
【问题描述】:

最近我发现自己经常使用 ECMA5 提供的新数组方法。我发现它必须经常重复的一项任务是在数组中找到满足特定条件的第一个(或唯一一个)对象。

您可以使用 Array.some 来检查它是否存在,但这只会返回一个布尔值。相反,我一直在使用 Array.filter,但这比循环效率低,因为它不会在找到项目时停止。有没有一种我错过的方法可以被破解成我想要的?

var things = [
    {name: "house"},
    {name: "table"},
    {name: "egg"},
    {name: "bob"},   
    {name: "hamster"}
];

var getBob = function(thing){
    return thing && thing.name == "bob";
};

// returns true not the object i want
console.log(things.some(getBob)); 
// returns the object but in an array and does not break when found
console.log(things.filter(getBob)[0]);  

【问题讨论】:

    标签: javascript arrays ecmascript-5


    【解决方案1】:

    在 ES5 中没有内置的方法。

    ES6 正在为此 http://people.mozilla.org/~jorendorff/es6-draft.html#sec-22.1.3.8 添加Array.prototype.find

    console.log(things.find(getBob));
    

    这是一个改编自https://gist.github.com/dcherman/5167353的polyfill

    (function() {    
        function polyfill(fnName) {
            if (!Array.prototype[fnName]) {
                Object.defineProperty(Array.prototype, fnName, {
                    value: function( predicate /*, thisArg */ ) {
                        var i, len, test, thisArg = arguments[ 1 ];
    
                        if ( typeof predicate !== "function" ) {
                            throw new TypeError();
                        }
    
                        test = !thisArg ? predicate : function() {
                            return predicate.apply( thisArg, arguments );
                        };
    
                        for( i = 0, len = this.length; i < len; i++ ) {
                            if ( test(this[i], i, this) === true ) {
                                return fnName === "find" ? this[ i ] : i;
                            }
                        }
    
                        if ( fnName !== "find" ) {
                            return -1;
                        }
                    },
                    enumerable: false,
                    writable: true,
                    configurable: true
                });
            }
        }
    
        [ 'find', 'findIndex' ].forEach(function(method) {
            polyfill(method);
        });
    }());
    

    我没有检查它是否符合草案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-27
      • 2014-06-07
      • 1970-01-01
      • 2021-09-07
      • 2017-04-15
      • 2022-10-25
      • 1970-01-01
      • 2020-05-13
      相关资源
      最近更新 更多