所以我想做的是 console.log 我的三个节点数组的一个特定元素。
const sentinel = document.querySelectorAll('.sentinel');
sentinel.forEach(function(element, index){
setInterval(function(element) {
if(index === 0){
console.log(element);
}
}, 3000);
});
我用谷歌搜索,找到了这篇文章:Get a specific element within forEach loop ,它确实问了同样的问题。但是,当我控制台记录元素时,我希望在 0 索引上获取节点。但是,我得到一个空元素。
最佳答案
您可以从 setInterval
中删除 element
,因为内部函数 setInterval
可以访问外部函数的变量,例如 element
。这种行为称为关闭。
此外,可以使用箭头函数来使您的代码更短更清晰。此外,arrow functions :
An arrow function does not have its own this. The this value of the enclosing lexical scope is used; arrow functions follow the normal variable lookup rules.
sentinel.forEach((element, index) => {
setInterval(() =>{
if (index === 0){
console.log(element);
}
}, 3000);
关于javascript - 如何使用 forEach 数组方法定位特定索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59590502/