簡體   English   中英

JavaScript - ForEach

[英]JavaScript - ForEach

我有一個JavaScript數組對象。 像這樣的東西:

var people = [
  { id:1, firstName: 'Joe', lastName: 'Smith' },
  { id:2, firstName: 'Bill', lastName: 'Smith' }
];

我正在使用forEach迭代人們。 這是我的代碼:

function doSomething() {
  people.forEach(function(person, self) {
    self.helpPerson(person);
  }, this);
}

function helpPerson(person) {
  alert('Welcome ' + person.firstName);
}

我試圖從forEach循環中調用helpPerson 但是,當我嘗試調用它時,我收到一條錯誤消息:

TypeError: self.helpPerson is not a function

如果我添加console.log(self); ,“0”被打印到控制台窗口。 這意味着我沒有正確傳遞我的參數。 或者,我誤解了閉包(就在我認為我完全理解它的時候:))。

那么,為什么不self退出?

您無需使用thisself或任何其他上下文調用helpPerson。 只需直接調用它:

var people = [
  { id:1, firstName: 'Joe', lastName: 'Smith' },
  { id:2, firstName: 'Bill', lastName: 'Smith' }
];

function doSomething() {
  people.forEach(function(person) {
    helpPerson(person);
  });
}

function helpPerson(person) {
  alert('Welcome ' + person.firstName);
}

當您登錄self的控制台,你所看到的“0”,因為它是印刷循環迭代的索引。

請參閱forEach的文檔 ,了解哪些回調傳遞給它的forEach函數。

通常, self用於捕獲閉包中的上下文( var self = this; )。 請參閱此問題的相關鏈接 ,因為這是一個非常重要的概念。

helpPerson是一個全局變量,而不是數組的屬性。

self.helpPerson(person); 應該是helpPerson(person);

forEach將兩個參數傳遞給回調:正在迭代的項及其索引。 這就是控制台記錄0的原因。

你期待this作為一個論點,當它實際上比那更神奇。 您可以使用this回調內,它將使用的任何情況下this你作為參數傳遞forEach

function doSomething() {
  people.forEach(function(person, index) {
    this.helpPerson(person); //Or for brevity, you can just remove `this` here
  }, this);
}

function helpPerson(person) {
  alert('Welcome ' + person.firstName);
}

forEach有2個參數:一個函數(val,index,arr)和一個this binding參數。

 people.forEach(function(person, self) {
    self.helpPerson(person); // self here would be array index number
  }, this);

您定義helpPerson()的方式可以像helpPerson(person);一樣直接調用它helpPerson(person);

請參閱評論

 var people = [ { id:1, firstName: 'Joe', lastName: 'Smith' }, { id:2, firstName: 'Bill', lastName: 'Smith' } ]; function doSomething() { people.forEach(function(person) { // no parameter for index required helpPerson(person); // just call the function }); // no other parameter is required } function helpPerson(person) { alert('Welcome ' + person.firstName); } doSomething(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM