Javascript:Array.prototype.find()的替代方案?

时间:2014-09-22 19:16:13

标签: javascript

我遇到一个问题,当我在AngularJS中使用.find()时,我的Chrome浏览器无效。这是我原来的问题:AngularJS: Array.prototype.find() does not work in Chrome

它在这条线上失败了:

      console.log($scope.products_colors); // prints `[Object]0: Objectlength: 1__proto__: Array[0]concat: function concat() { [native code] }constructor: function Array() { [native code] }every: function every() { [native code] }filter: function filter() { [native code] }forEach: function forEach() { [native code] }indexOf: function indexOf() { [native code] }join: function join() { [native code] }lastIndexOf: function lastIndexOf() { [native code] }length: 0map: function map() { [native code] }pop: function pop() { [native code] }push: function push() { [native code] }reduce: function reduce() { [native code] }reduceRight: function reduceRight() { [native code] }reverse: function reverse() { [native code] }shift: function shift() { [native code] }slice: function slice() { [native code] }some: function some() { [native code] }sort: function sort() { [native code] }splice: function splice() { [native code] }toLocaleString: function toLocaleString() { [native code] }toString: function toString() { [native code] }unshift: function unshift() { [native code] }__proto__: Object mens_detail_controller.js?body=1:24`

      $scope.selected_color = $scope.products_colors.find(function(el) {
        return el.id == 91;
      });

我知道它在.find上失败了,因为当我用其他东西替换它时,代码就会起作用。

是否有替代方法可以查看数组并在javascript中抓取具有特定条件的第一个元素?

2 个答案:

答案 0 :(得分:12)

正如elclanrs在评论中指出的那样,xs.filter(f)[0]可以替代xs.find(f)

答案 1 :(得分:11)

以下是MDN's polyfill

if (!Array.prototype.find) {
  Array.prototype.find = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.find called on null or undefined');
    }
    if (typeof predicate !== 'function') {
      throw new TypeError('predicate must be a function');
    }
    var list = Object(this);
    var length = list.length >>> 0;
    var thisArg = arguments[1];
    var value;

    for (var i = 0; i < length; i++) {
      value = list[i];
      if (predicate.call(thisArg, value, i, list)) {
        return value;
      }
    }
    return undefined;
  };
}