我在数组上使用 forEach 方法,我想让数组项的值为“this”。
当我将下面代码中的“item”更改为=“this”时,什么也没有发生。
是否可以使用 forEach 方法来执行此操作,或者我正在尝试执行的操作是不可能的?
我已经简化了我正在使用的实际代码中的问题,以免增加进一步的复杂性(在实际代码中,数组项控制一系列滚动触发器,我需要其中每一个都具有值“this” ')。
在下面的示例中,我只需要使用“this”来更改背景颜色。
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>
最佳答案
您可以设置this
的值在回调中,但您不能在每次迭代时将其设置为新项目。这是不必要且多余的,因为该参数就是为此目的而存在的。
in the actual code the array items control a series scroll triggers and I need each one of these to have the value '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()
变成this
doStuff
的值.
关于javascript - 为 forEach 方法中的数组项赋予值 'this' (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46879394/