简体   繁体   English

如何使用 setTimeout 在数字数组上像 cos 图一样循环两次

[英]How can i loop twice like cos graph over array of numbers with setTimeout

I have an array of numbers like this:我有一个这样的数字数组:

const numbers = [.1, .2, .3, .4, .5, .6, .7, .8, .9, 1];

What I'd like to do is something like this graph:我想做的是这样的图表:

cos图

What I've achieved:我所取得的成就:

const cosNumbers = (reverse) => {
(reverse ? numbers.reverse() : numbers).forEach((number) => {
 ((index) => {
   setTimeout(() => { console.log(index) }, index * 1000);
 })(number);
});
};

cosNumbers();
cosNumbers(true);

I can get the first function results as i want to be.我可以获得我想要的第一个函数结果。 but the second one cannot, because I'm reversing the numbers from smaller to biggest numbers, so smallest number will trigger earlier than larger in setTimeout().但第二个不能,因为我正在将数字从小到大反转,所以最小的数字将比 setTimeout() 中的大数字更早触发。 This is simple function but I don't know why is it so challenging to me :(这是一个简单的功能,但我不知道为什么它对我来说如此具有挑战性:(

The problem is that you are passing in the number into your IIFE but using it as an index.问题是您将数字传入您的 IIFE,但将其用作索引。 They are different: the number refers to the actual values of the array, while index refers to their positions in the array.它们是不同的: numberindex组的实际值,而index是指它们在数组中的位置。

Remember that the index is accessible as the second argument in the .forEach() callback.请记住,索引可作为.forEach()回调中的第二个参数访问。 So you should access number and index separately as such: .forEach((number, index) => ...)所以你应该分别访问numberindex.forEach((number, index) => ...)

I believe what you wanted is this:我相信你想要的是这个:

setTimeout(() => console.log(number), index * 1000);

Because you want to:因为你想:

  • Log the actual value (the item in the array)记录实际值(数组中的项目)
  • Use the index of the item to time their appearance使用项目的索引来确定它们的出现时间

 const numbers = [.1, .2, .3, .4, .5, .6, .7, .8, .9, 1]; const cosNumbers = (reverse) => { (reverse ? numbers.reverse() : numbers).forEach((number, index) => { setTimeout(() => console.log(number), index * 1000); }); }; cosNumbers(); cosNumbers(true);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM