Array.prototype.filter的Monkey补丁打破了AngularJS 1.6 [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

ngSwitchWhen抛出错误'无法读取属性'未定义'的NaN'

我在Array原型上覆盖现有的filter方法,这适用于angular 1.5.7版本。最近我把它升级到1.6.10。相同的代码无法正常工作,并在浏览器控制台中抛出错误Cannot read property 'NaN' of undefined

HTML

  <select ng-model="selection" ng-options="item for item in items">
  </select>
  <code>selection={{selection}}</code>
  <hr/>
  <div class="animate-switch-container"
    ng-switch on="selection">
      <div class="animate-switch" ng-switch-when="settings|options" ng-switch-when-separator="|">Settings Div</div>
      <div class="animate-switch" ng-switch-when="home">Home Span</div>
      <div class="animate-switch" ng-switch-default>default</div>
  </div>

调节器

 Array.prototype.filter = function (predicateFunction) {
   let results = [];
      this.forEach((item) => {
        if (predicateFunction(item)) {
          results.push(item);
        }
      });
    return results;
  };

  $scope.items = ['settings', 'home', 'options', 'other'];
  $scope.selection = $scope.items[0];

我在plunker中重现了这个问题。

javascript arrays angularjs angularjs-directive angularjs-1.6
1个回答
0
投票

你的Array.prototype.filter猴子补丁是有缺陷的:

 Array.prototype.filter = function (predicateFunction) {
   let results = [];
      ̶t̶h̶i̶s̶.̶f̶o̶r̶E̶a̶c̶h̶(̶(̶i̶t̶e̶m̶)̶ ̶=̶>̶ ̶{̶
      this.forEach((item,index,array) => {
        ̶i̶f̶ ̶(̶p̶r̶e̶d̶i̶c̶a̶t̶e̶F̶u̶n̶c̶t̶i̶o̶n̶(̶i̶t̶e̶m̶)̶)̶ ̶{̶
        if (predicateFunction(item,index,array)) {
          results.push(item);
        }
      });
    return results;
  };

应该使用三个参数调用回调:

  • 元素的价值
  • 元素的索引
  • 正在遍历的Array对象

Update

ES5标准建议使用此填充物:

if (!Array.prototype.filter){
  Array.prototype.filter = function(func, thisArg) {
    'use strict';
    if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) )
        throw new TypeError();

    var len = this.length >>> 0,
        res = new Array(len), // preallocate array
        t = this, c = 0, i = -1;
    if (thisArg === undefined){
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          if (func(t[i], i, t)){
            res[c++] = t[i];
          }
        }
      }
    }
    else{
      while (++i !== len){
        // checks to see if the key was set
        if (i in this){
          if (func.call(thisArg, t[i], i, t)){
            res[c++] = t[i];
          }
        }
      }
    }

    res.length = c; // shrink down array to proper size
    return res;
  };
}

有关更多信息,请参阅MDN JavaScript Reference - Array.prototype.filter polyfill

© www.soinside.com 2019 - 2024. All rights reserved.