【问题标题】:Unable to create an array dynamically using foEach无法使用 forEach 动态创建数组
【发布时间】:2019-12-16 05:30:51
【问题描述】:

在下面的代码中,当我控制台calculateTips() 的值时,我收到以下错误

未捕获的类型错误:无法设置未定义的属性“0”

let tipCal = {
  bills: [124, 48, 268, 180, 42],
  calculateTips: function() {
    this.tips = [];
    this.finalValue = [];
    (this.bills).forEach(function(item, index) {
      if (item < 50) {
        this.tips[index] = (item * .2);
      } else if (item >= 50 && item < 200) {
        this.tips[index] = (item * .15);
      } else {
        this.tips[index] = (item * .1);
      }
    });
    return this.tips;

  }
}

我无法理解为什么会出现此错误,因为根据我的说法,我正在做正确的事情。请帮忙。

【问题讨论】:

标签: javascript arrays object foreach


【解决方案1】:

有几点需要注意。首先,据我所知,使用索引表示法而不是 Array.prototype.push 并不是很常见。由于您是从头开始构建this.tips,因此您可以使用this.tips.push(...)。使用push 有时也可以获得更好的性能。见这里:Why is array.push sometimes faster than array[n] = value?

其次,是的,function 的使用会改变this 的上下文,所以forEach 回调中的this 指的是回调函数而不是tipCal。按照建议使用箭头函数将保留this 的上下文。

【讨论】:

    【解决方案2】:

    您可以通过这样做来实现您的结果。根据需要使用。

    var num = 10,
      dynar = [...Array(num)].map((_,i) => ++i+"");
    console.log(dynar);
    

    输出:[“1”,“2”,“3”,“4”,“5”,“6”,“7”,“8”,
    “9”,“10”]

    【讨论】:

      【解决方案3】:

      .forEach回调函数替换为=&gt;(arrow)函数

      试试这个:

        let tipCal = {
          bills: [124, 48, 268, 180, 42],
          calculateTips: function () {
            this.tips = [];
            this.finalValue = [];
            (this.bills).forEach((item, index)=> {
              if (item < 50) {
                this.tips[index] = (item * .2);
              } else if (item >= 50 && item < 200) {
                this.tips[index] = (item * .15);
              } else {
                this.tips[index] = (item * .1);
              }
            });
            return this.tips;
      
          }
        }
        console.log(tipCal.calculateTips())

      【讨论】:

        【解决方案4】:

        我认为这是因为函数内部的函数更改了this 关键字。

        .forEach(function(item, index) { 住在calculateTips: function() { 里面。 尝试使用箭头函数,它会是.forEach((item, index) =&gt; {

        箭头函数不会改变this关键字。

        所以它会返回..

        (5) [18.599999999999998, 9.600000000000001, 26.8, 27, 8.4]

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-06-23
          • 2016-11-06
          • 1970-01-01
          • 1970-01-01
          • 2015-07-18
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多