ES5有效地等同于ES6我的lambda搜索?

时间:2015-07-31 11:16:31

标签: javascript angularjs ecmascript-6

我在数组上进行了es6搜索并且无法弄清楚将其重写为es5,因为cordova不允许我使用lambda ......

$scope.Contact.title = $scope.doctitles[$scope.doctitles.findIndex(x => x.id == $localStorage.data.contacts[$localStorage.data.itemID].title.id)];

1 个答案:

答案 0 :(得分:4)

$scope.Contact.title = $scope.doctitles[$scope.doctitles.findIndex(function(x) {
    return x.id == $localStorage.data.contacts[$localStorage.data.itemID].title.id;
})];

您只需使用函数替换lambda。

编辑:由于findIndex也是ES6,您可以使用此polyfill:

if (!Array.prototype.findIndex) {
  Array.prototype.findIndex = function(predicate) {
    if (this == null) {
      throw new TypeError('Array.prototype.findIndex 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 i;
      }
    }
    return -1;
  };
}

取自https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex