【问题标题】:ES5 effectively equivalent to ES6 my lambda search?ES5 等效于 ES6 我的 lambda 搜索?
【发布时间】:2015-07-31 11:16:30
【问题描述】:

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

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

【问题讨论】:

    标签: javascript angularjs ecmascript-6


    【解决方案1】:
    $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

    【讨论】:

    • .findIndex() 也是 ES6 的一部分
    • @ralh:你自己写的 polyfill 吗?如果不是,请引用(链接)您从哪里复制它。
    猜你喜欢
    • 2018-04-05
    • 2015-05-31
    • 1970-01-01
    • 2019-11-29
    • 2018-08-29
    • 1970-01-01
    • 1970-01-01
    • 2015-02-09
    • 1970-01-01
    相关资源
    最近更新 更多