【问题标题】:Unable to print items from two arrays in intervals无法间隔打印两个数组中的项目
【发布时间】:2021-05-20 11:17:46
【问题描述】:

所以我有两个数组,每个数组的项数相同。我一直在尝试在控制台中间隔打印这些项目。像这样的:

1
Bruce Wayne
45

然后每隔一秒就会打印出来:

2
Clark Kent
43


and so on till the last item. 

打印完所有项目后停止。

现在我得到这样的东西:

1
Clark Kent
43


3
undefined

所以这是我尝试过的代码:

const superheroes = [
    {
        "name": "Bruce Wayne",
        "age": 45
    },
    {
        "name": "Clark Kent",
        "age": 43
    },
    {
        "name": "Oliver Queen",
        "age": 41
    },
    ,
    {
        "name": "Barry Allen",
        "age": 25
    }
];

const arr = [
    '1',
    '2',
    '3',
    '4'
];
const startBtn = document.querySelector('#start');
let index                       = 0;


$(startBtn).click(() => {
        const interval = setInterval(() => {
            const arrItem       = arr[index++];
            const superheroItem = superheroes[index++];
            
            console.log(arrItem);
            console.log(superheroItem);

            if(index == arr.length){
                clearInterval(interval);
            }
        }, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start">Start</button>

我该如何解决?

【问题讨论】:

  • 您使用后增量运算符的方式存在问题。检查这个以了解它的工作developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
  • 需要修复什么?当你运行它时会发生什么?顺便说一句,当您使用index++ 增加索引时,它会在您使用该变量后增加,因此如果您从 0 开始,arrItem 将是 arr[0] 而 superHeroItem 将是超级英雄 [1]。您的下一个 arrItem 将是 arr[2],superHeroItem 将是 superHeroes[3],依此类推。
  • @AHMEDSAJJAD 哦,我明白了。有什么解决办法吗?
  • @user1599011 如果您不介意,请阅读这篇文章吗?我已经提供了那里的一切。

标签: javascript jquery arrays object


【解决方案1】:

基本上,您需要在代码之后增加索引。 尝试在 superheroes 集合上使用某种循环重写此代码。

const superheroes = [
    {
        "name": "Bruce Wayne",
        "age": 45
    },
    {
        "name": "Clark Kent",
        "age": 43
    },
    {
        "name": "Oliver Queen",
        "age": 41
    },
    {
        "name": "Barry Allen",
        "age": 25
    }
];

const arr = [
    '1',
    '2',
    '3',
    '4'
];
const startBtn = document.querySelector('#start');
let index                       = 0;


$(startBtn).click(() => {
        const interval = setInterval(() => {
            let arrItem       = arr[index];
            let superheroItem = superheroes[index];
            
            console.log(arrItem);
            console.log(superheroItem);

            if(index === arr.length - 1){
                clearInterval(interval);
            }
            
            index ++;
        }, 1000);
       
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start">Start</button>

【讨论】:

  • if (++index === arr.length)
  • @Oleksandr Mate,它不起作用。打印的第一项是 0 而不是 1,因为 arr 中的第一项是 1,
  • @zak,由于拼写错误。他有const arr = ["0", "1", ...]
  • @Zak 它已针对 1,2..etc 进行了修复。
【解决方案2】:

您正在重用索引变量并多次递增它。因为数组是零索引的,所以您不想在第一次打印之前增加数组。然后每次循环只增加一次。

你的超级英雄数组中还有一个额外的逗号。

const superheroes = [
        {
            "name": "Bruce Wayne",
            "age": 45
        },
        {
            "name": "Clark Kent",
            "age": 43
        },
        {
            "name": "Oliver Queen",
            "age": 41
        },
        {
            "name": "Barry Allen",
            "age": 25
        }
    ];

const arr = [
  '1',
  '2',
  '3',
  '4'
];
const startBtn = document.querySelector('#start');
let index                       = 0;


$(startBtn).click(() => {
  const interval = setInterval(() => {
    const arrItem       = arr[index];
    const superheroItem = superheroes[index];

    console.log("index: ",index);
    console.log(arrItem);
    console.log(superheroItem);

    index++

    if(index == arr.length){
      clearInterval(interval);
    }
  }, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="start">Start</button>

【讨论】:

    【解决方案3】:

    没有必要像这样递增:

    const arrItem       = arr[index++];
    const superheroItem = superheroes[index++];
    

    应该是:

    const arrItem = arr[index];
    const superheroItem = superheroes[index];
    
    index++;
    

    因为对应的数据在两个数组中的索引相同。

    另外,我建议使用for 循环来迭代数组,而不是使用手动计数器的setInterval(它有助于避免此类错误)。如果您确实需要在循环的每次迭代之间延迟 1 秒,那么一种更现代的处理方法可能是在每次迭代时等待超时,如下所示:

    const superheroes = [{
        "name": "Bruce Wayne",
        "age": 45
      },
      {
        "name": "Clark Kent",
        "age": 43
      },
      {
        "name": "Oliver Queen",
        "age": 41
      },
      {
        "name": "Barry Allen",
        "age": 25
      }
    ];
    
    const arr = [
      '1',
      '2',
      '3',
      '4'
    ];
    
    async function handleStartBtnClick(e) {
      //Remove the handler, so clicking the button multiple times does nothing
      e.target.removeEventListener('click', handleStartBtnClick);
      //Disable the button and give and informational message
      e.target.disabled = true;
      msgSpan.insertAdjacentHTML('afterbegin', '<font color="red">Please wait until current rollcall completes..</font>');
    
      await doHeroRollcall();
      //Add the handler back now that we're ready to call it again
      e.target.addEventListener('click', handleStartBtnClick);
      //Enable the button and give and clear informational message
      e.target.disabled = false;
      msgSpan.innerHTML = "";
    }
    
    async function doHeroRollcall() {
      console.clear();
    
      for (let i = 0; i < superheroes.length; i++) {
        console.log(`name = ${superheroes[i].name}, age = ${superheroes[i].age} - ${arr[i]}`);
        await doTimeout();
      }
    }
    
    function doTimeout() {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          resolve();
        }, 1000);
      });
    }
    
    const startBtn = document.querySelector('#start');
    const msgSpan = document.querySelector('#msg');
    
    startBtn.addEventListener('click', handleStartBtnClick);
    <button id="start">Start</button>
    <span id="msg"></span>

    这样您就不必担心在代码中的某处调用clearInterval()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多