在forEach方法中为数组项赋值' this' (JavaScript的)

时间:2017-10-22 21:35:51

标签: javascript arrays foreach this

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

当我更改' item'在下面的代码中='这个'什么都没发生。

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

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

在下面的示例中,我只需要使用'这个'改变背景颜色。

Codepen链接在这里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>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:1)

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

  

在实际代码中,数组项控制着一系列滚动触发器,我需要其中的每一个都具有值&#39;这&#39;

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

&#13;
&#13;
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";
}
&#13;
.div {
  height: 50px;
  width: 50px;
  background-color: red;
  margin-bottom: 10px;
}
&#13;
<div class="div" id="div1"></div>
<div class="div" id="div2"></div>
<div class="div" id="div3"></div>
&#13;
&#13;
&#13;

我们使用.call()来调用doStuff(),以便.call()的第一个参数成为this的{​​{1}}值。

答案 1 :(得分:1)

Array.prototype.forEachjQuery的{​​{1}}函数不同,因为each将项目从数组传递,该项目的索引和数组本身传递给其回调函数。所以回调应该是这样的:

forEach

function(item, index, array) 不同,forEach不会将项目each传递给其回调,因此您必须使用this。因此,由于您未将item参数指定为this且该函数似乎未绑定到任何forEach,因此其中的this将引用this

那个beign说,你的代码应该是:

window

注意:

如@newToJs所述,您可以使用myArray.forEach(function(item){ item.style.backgroundColor = "blue"; // ^^^^ item is the current item from the array myArray }); document.getElementsByClassName一次性获取所有div,而不是使用document.querySelectorAll逐个获取它们:

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;
}