javascript - 如何使用 forEach 数组方法定位特定索引?

标签 javascript arrays

所以我想做的是 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/

相关文章:

javascript - andThen 和 click 助手的 Ember.JS 集成测试问题

javascript - 使用 jquery 突出显示文本

javascript - 无法使用 CSS-Approach 或 JQuery-Apprach 将必需的验证添加到文本区域

c++ - 从 TCP 客户端发送的双数组

python - np.unique 中更快的 return_inverse

javascript - 使用 DOM 对象创建备份数组

javascript - 数组,独立修改数组中的单词

c - 确定C中字符数组的大小

javascript - 如何用javascript改变底部的样式?

javascript - Chrome 断点停止工作 - 查看带有 VM 前缀的不同文件