如何将未知数量的数组的索引整数设置为变量

时间:2019-05-01 22:59:56

标签: javascript arrays loops

我有一个数组,其中包含n个对象(让我们说n = 1),以及一个forEach函数,该函数每次循环时都会执行另一个函数(基本上,数组中的对象数量是其调用的次数) )。但麻烦的是,我需要将数组的每个索引整数分配给一个变量,以便可以将其传递给其他函数。有谁知道我该怎么做(循环不必是forEach)?

我尝试将数组的索引设置为变量,但这最终解析为最终索引,我需要将每个索引都设置为变量。

let tasks = {"options":[{"headless":false"},{"headless":true}]};

tasks.options.forEach(function(value, int) {


    //the function called every${int}times
    main();

    //this returns 1 if there is 2 objects. i need to be able to have a variable(s?) that equals tasks.options[0]
    //and tasks.options[1] simultaneously
    let check = tasks.options[int]


});

2 个答案:

答案 0 :(得分:0)

也许使用json对象?我不确定这是否是您需要的,但是您可以做到,以便每个json元素都等于数组{"0": i[0], "1": i[1] "3": i[2], "4": ...}

中的值。
let jsonObj = JSON.parse("{}");

tasks.options.forEach((value, int)) => {
    jsonObj[int.toString()] = value;
}

将是我最好的例子。

答案 1 :(得分:0)

编辑:关于puppeteer模块,将我的forEach()循环使用以及将不同的JSON值提供给多个puppeteer.launch( )处决。相反,我使用了for循环,并在for循环内定义了我的函数。这解决了任何问题。对此我感到抱歉,并感谢大家。是时候回馈社区了:)