简体   繁体   English

动态确定for循环的顺序

[英]Dynamically decide order of for loop

I need to be able to dynamically read an array from either the start or the end, and work up or down from that position. 我需要能够从开头或结尾动态读取数组,并从该位置向上或向下工作。

This is decided by a boolean: var startFromBeginOfChat = true; 这是由布尔值决定的: var startFromBeginOfChat = true;

I tried to pass a statement inside the for loop, like so: 我试图在for循环中传递一条语句,如下所示:

for (var i = startFromBeginOfChat ? (parsedChat.messages.length - 1):0; 
startFromBeginOfChat ? (i >= 0):(i < parsedChat.messages.length); 
startFromBeginOfChat ? i--:i++) 

Is there any other way to dynamically fire either one or another for loop? 还有其他方法可以动态触发一个或另一个for循环吗? I could of course store the entire logic into an if/else statement but since the logic inside the for loop is exactly the same, I'd rather not. 我当然可以将整个逻辑存储到if/else语句中,但是由于for循环中的逻辑完全相同,所以我宁愿不这样做。

As stated in the comments, you can just reverse the list beforehand if you need to parse it backwards. 如评论中所述,如果您需要向后解析列表,则可以事先将其反向。 The entire final code would be the following: 完整的最终代码如下:

if (!startFromBeginOfChat) parsedChat.messages.reverse();

for (var i = 0; i < parsedChat.messages.length; i++) {
   // code
}

If you need the original list to be in order again, you could either reverse it again at the end (potentially more efficient, but less semantic) or create a new copy before you originally reverse it by using parsedChat.messages.slice() (more readable in my opinion). 如果您需要重新排列原始列表,则可以在末尾再次反转它(可能更有效,但语义要少一些),或者在使用parsedChat.messages.slice()原始反转之前创建一个新副本。我认为更具可读性)。

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

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