简体   繁体   English

遍历数组并打印特定范围的值?

[英]Loop through an array and print a specific range of values?

var months = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October","November", "December"];
// For Loop
for (var i = 0; i = months.slice(4, 8); i++) {
alert(a);

I'm trying to loop through this array and alert the values in a specific range, May - August. 我正在尝试遍历此数组,并在5月-8月的特定范围内提醒值。 I can't seem to figure this out. 我似乎无法弄清楚。 Thanks! 谢谢!

For a for loop, specify your start index (May = 4) and end index (August = 7), and use this pattern: 对于for循环,请指定您的开始索引(May = 4)和结束索引(August = 7),并使用以下模式:

var months = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October","November", "December"];
// For Loop
for (var i = 4; i <= 7; i++) {
  alert(months[i]);
}

If you just want those items, and you know the contents of the array, you have a few options: 如果只需要这些项目,并且知道数组的内容,则可以选择以下几种方法:

var months = ["January", "February", "March", "April",
              "May", "June", "July","August", "September",
              "October","November", "December"];

// For Loop
for (var i = 4; i <= 7; i++) {
   alert(months[i]);
}

There's no need to slice while using the for loop. 使用for循环时无需切片。 You already know which indices you're interested in, so you can just iterate across that range. 您已经知道您感兴趣的索引,因此您可以在该范围内进行迭代。 It's also the most efficient of these choices, generally. 通常,它也是这些选择中最有效的。

// Slice and for-loop
var selected = months.slice(4,7);
for (var i = 0; i < selected.length; i++) {
   alert(selected[i]);
}

You could slice first and then iterate across the whole (new) array in a for loop. 您可以先进行切片,然后在for循环中遍历整个(新)数组。 Generally, you wouldn't do this. 通常,您不会这样做。 However, if your conditions for narrowing the array were more complex, there might be reasons to build the array out first and then loop over it, so here's a clean example of how to do that. 但是,如果缩小阵列的条件更加复杂,则可能有理由先构建阵列然后在其上循环,因此这里是一个清晰的示例。

// Slice and forEach
months.slice(4,7).forEach(function(x) {alert(x);});

This would be my personal choice, because it's concise. 这是我个人的选择,因为它很简洁。 It's effectively the same as the slice-and-loop example (slightly less performant, but not in a way you're ever likely to need to care about), just expressed using Array.prototype.forEach() instead of a separate for loop. 它实际上与slice-and-loop示例相同(性能稍差,但并不是您可能需要关心的方式),只是使用Array.prototype.forEach()而不是单独的for循环表示。

You need to store the sliced array in a temporary variable and loop over that. 您需要将切片的数组存储在一个临时变量中并对其进行循环。

Example: https://jsfiddle.net/epkkstqz/1/ 示例: https//jsfiddle.net/epkkstqz/1/

var months = ["January", "February", "March", "April", "May", "June", "July","August", "September", "October","November", "December"];

for (var i = 0, slice = months.slice(4, 8); i < slice.length; i++) {
  alert(slice[i]);
}

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

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