【问题标题】:Javascript forEach returning "undefined" as object variablesJavascript forEach 返回“未定义”作为对象变量
【发布时间】:2016-10-21 00:08:03
【问题描述】:

我正在尝试实现对 forEach 的简单调用,以在汽车数组中的所有项目上运行 logMe 函数。输出是意外的。所有变量都读取“未定义”。

    function Automobile(year, make, model, type) {
      this.year = year;
      this.make = make;
      this.model = model;
      this.type = type;
    }

    Automobile.prototype.logMe = function(boolVal) {
      if (boolVal == true) {
        console.log(this.year + ' ' + this.make + ' ' + this.model + ' ' + this.type);
      } else {
        console.log(this.year + ' ' + this.make + ' ' + this.model);
      }
    }

    var automobiles = [
      new Automobile(2010, "Toyota", "Tacoma", "Pickup"),
      new Automobile(2005, "Lotus", "Elise", "Roadster"),
      new Automobile(2008, "Subaru", "Outback", "Wagon")
    ];

    automobiles.forEach(Automobile.prototype.logMe.bind(true)); //the problem
    automobiles[0].logMe(true); //test logMe function

输出:

未定义未定义未定义

未定义未定义未定义

未定义未定义未定义

1995 年本田雅阁轿车

【问题讨论】:

标签: javascript arrays foreach


【解决方案1】:

Function.bind() 的第一个参数是函数内this 的值。在您的示例中,this 绑定到 true,这就是为什么您会为属性值获得 undefined

forEach 将元素作为第一个参数传递给回调。因此,您可以定义一个在其第一个参数上调用 logMe 的 lambda,而不是传递绑定方法。

automobiles.forEach(function(car, i, cars) {car.logMe(true);});

【讨论】:

  • 你能解释一下这三个变量是什么吗?
  • 你能解释一下这三个变量是什么吗? (car, i, cars) car = 索引处的对象,i = 索引,汽车是什么?
  • @user3612719 它是“汽车”数组。传递给.forEach 回调的第三个参数是被迭代的数组。
【解决方案2】:

Function.prototype.bind 创建一个新函数,您必须传入 this 的值 - 调用该函数的构造。

如果你想创建一个以后可以像这样调用的函数数组,你应该像下面那样使用bind,否则只需调用forEach中的函数。

var caller = [];
automobiles.forEach(function(element) {
  caller.push(Automobile.prototype.logMe.bind(element));
}, caller);
caller[0](true);

下面的演示:

function Automobile(year, make, model, type) {
  this.year = year;
  this.make = make;
  this.model = model;
  this.type = type;
}

Automobile.prototype.logMe = function(boolVal) {
  if (boolVal == true) {
    console.log(this.year + ' ' + this.make + ' ' + this.model + ' ' + this.type);
  } else {
    console.log(this.year + ' ' + this.make + ' ' + this.model);
  }
}

var automobiles = [
  new Automobile(2010, "Toyota", "Tacoma", "Pickup"),
  new Automobile(2005, "Lotus", "Elise", "Roadster"),
  new Automobile(2008, "Subaru", "Outback", "Wagon")
];

var caller = [];

automobiles.forEach(function(element) {
  caller.push(Automobile.prototype.logMe.bind(element));
}, caller);

caller[0](true); //test logMe function

【讨论】:

    猜你喜欢
    • 2012-01-16
    • 2019-05-03
    • 1970-01-01
    • 2023-01-11
    • 2019-11-28
    • 2013-09-24
    • 2019-02-17
    • 1970-01-01
    • 2018-06-06
    相关资源
    最近更新 更多