簡體   English   中英

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

[英]Javascript: Alternative to Array.prototype.find()?

我有一個問題,當我在AngularJS中使用它時, .find()無法在我的Chrome瀏覽器上運行。 這是我最初的問題: AngularJS:Array.prototype.find()在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中抓取具有特定條件的第一個元素?

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

這是MDN的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;
  };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM