Javascript:在循环时将值添加到数组中,然后该值也将包含在循环中 [英] Javascript: add value to array while looping that will then also be included in the loop

查看:60
本文介绍了Javascript:在循环时将值添加到数组中,然后该值也将包含在循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果这是一个重复项,似乎找不到它.

Sorry if this is a dupplicate, can't seem to find it.

var a = [1,2,3,4];
a.forEach(function(value){
  if(value == 1) a.push(5);
  console.log(value);
});

我想知道是否存在一种方法(任何类型的循环或数据类型),以便在循环期间(或以任何顺序,只要所有5个数字都在其中)输出1 2 3 4 5

I wonder if there is a way (any sort of loop or datatype) so that this will ouput 1 2 3 4 5 during the loop (or in any order, as long as all the 5 numbers are in there)

推荐答案

使用 Array.prototype.forEach()将回调应用于附加到元素的元素,或在执行期间从数组中删除.根据规范:

Using Array.prototype.forEach() will not apply the callback to elements that are appended to, or removed from, the array during execution. From the specification:

forEach 处理的元素范围设置在第一个元素之前调用 callbackfn .在数组之后附加到数组的元素呼叫 forEach 开始的呼叫不会被 callbackfn 访问.

The range of elements processed by forEach is set before the first call to callbackfn. Elements which are appended to the array after the call to forEach begins will not be visited by callbackfn.

但是,您可以使用标准的 for 循环,并在每次迭代期间有条件地检查数组的当前长度:

You can, however, use a standard for loop with the conditional checking the current length of the array during each iteration:

for (var i = 0; i < a.length; i++) {
    if (a[i] == 1) a.push(5);
    console.log(a[i]);
}

这篇关于Javascript:在循环时将值添加到数组中,然后该值也将包含在循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆