[英]How to call an external variable in a forEach loop in javascript
I'm trying to call an external variable in a forEach context. 我正在尝试在forEach上下文中调用外部变量。 Since I'm using an arrow notation this should make the trick but the variable still comes out as undefined. 由于我使用的是箭头符号,因此应该可以解决问题,但是变量仍未定义。
This is my code: 这是我的代码:
transformSlots (slots) {
var array = slots;
var newArray;
array.forEach(element => {
var newElement = {
day: dateFns.getDate(element.slot),
month: dateFns.getMonth(element.slot),
year: dateFns.getYear(element.slot),
hour: dateFns.getHours(element.slot),
numInterview: element.num,
id_users_pending: 0,
id_users_accepted: 0
};
this.newArray.push(newElement);
});
return array;
}
EDIT: If I take .this away the result is exactly the same. 编辑:如果我拿走.this,结果是完全一样的。
Remove the this
. 删除this
。 It will make the code look for newarray in the callback and not outside the loop 它将使代码在回调中而不是循环外查找newarray
transformSlots (slots) { var array = slots; var newArray; array.forEach(element => { var newElement = { day: dateFns.getDate(element.slot), month: dateFns.getMonth(element.slot), year: dateFns.getYear(element.slot), hour: dateFns.getHours(element.slot), numInterview: element.num, id_users_pending: 0, id_users_accepted: 0 }; newArray.push(newElement); }); return array; }
You should use newArray.push(newElement);
您应该使用newArray.push(newElement);
instead of this.newArray.push(newElement);
而不是this.newArray.push(newElement);
. 。
If you print this
in the forEach
loop you'll find that the newArray
isn't bind to this
. 如果在forEach
循环中打印this
,则会发现newArray
未绑定到this
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.