为 forEach 方法中的数组项指定值 'this' (javascript)



我在数组上使用forEach方法,我想使数组项具有值"this"。

当我将下面代码中的"item"更改为="this"时,没有任何反应。

是否可以使用 forEach 方法执行此操作,或者我正在尝试做的事情是不可能的?

我已经从我正在使用的实际代码中简化了问题,以免增加进一步的复杂性(在实际代码中,数组项控制一系列滚动触发器,我需要其中每个都具有值"this")。

在下面的示例中,我只需要使用"this"来更改背景颜色。

代码笔链接在这里 https://codepen.io/emilychews/pen/boJBKB

var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var myArray = [div1, div2, div3]
myArray.forEach(function(item) {
  item = this;
  this.style.backgroundColor = "blue";
})
.div {
  height: 50px;
  width: 50px;
  background-color: red;
  margin-bottom: 10px;
}
<div class="div" id="div1"></div>
<div class="div" id="div2"></div>
<div class="div" id="div3"></div>

可以在回调中设置 this 的值,但不能在每次迭代时将其设置为新项。这将是不必要和多余的,因为该参数是为此目的而存在的。

在实际代码中,数组项控制一系列滚动触发器,我需要其中每个项都具有值"this"

至于你提到的实际情况,你需要提供更多细节。一个单独的功能可能就足够了。

var div1 = document.getElementById('div1');
var div2 = document.getElementById('div2');
var div3 = document.getElementById('div3');
var myArray = [div1, div2, div3];
myArray.forEach(function(item) {
  doStuff.call(item);
});
function doStuff() {
  this.style.backgroundColor = "blue";
}
.div {
  height: 50px;
  width: 50px;
  background-color: red;
  margin-bottom: 10px;
}
<div class="div" id="div1"></div>
<div class="div" id="div2"></div>
<div class="div" id="div3"></div>

这里我们使用.call()来调用doStuff(),这样.call()的第一个参数就变成了doStuffthis值。

Array.prototype.forEach

jQueryeach函数不同,因为forEach将数组中的项目、该项目的索引和数组本身传递给其回调函数。所以回调应该是这样的:

function(item, index, array)

forEacheach 不同,不会将项目作为回调this传递,因此您必须使用 item 。因此,由于您没有指定要forEachthis参数,并且该函数似乎没有绑定到任何this,因此其中的this将引用window

也就是说,你的代码应该是:

myArray.forEach(function(item){
    item.style.backgroundColor = "blue";
//  ^^^^ item is the current item from the array myArray
});

注意:

正如@newToJs所提到的,您可以使用document.getElementsByClassNamedocument.querySelectorAll一次性获取所有div,而不是使用document.getElementById逐个获取它们:

var divs = document.querySelectorAll(".div");
// divs is not an array (it is a NodeList which is an array-like object) that does not have a forEach function (at least not in some older browsers), so we have to use .call of forEach like so
[].forEach.call(divs, function(item) {
  item.style.backgroundColor = "blue";
});
.div {
  height: 50px;
  width: 50px;
  background-color: red;
  margin-bottom: 10px;
}
<div class="div" id="div1"></div>
<div class="div" id="div2"></div>
<div class="div" id="div3"></div>

最新更新