在获取请求的 for 循环中,如何将 "i" 值传递给在循环外定义为模板文字的主体有效负载?

In for loop of fetch requests, how do you pass "i" value into body payload that's been defined as template literal outside the loop?

我想发出多个获取请求,每个请求都有不同的负载,本例中为 studentID。每个循环都会更改 studentID,但为了可读性,有效负载被定义为循环外的模板文字变量。有没有办法将 for 循环迭代器值获取到有效负载(在外部定义)?

var payload=`{"studentID": ${studentID}}` //expecting studentID to be iterated in loop
var myInit = {
    method: 'POST',
    headers: {
       'Accept': 'application/json, text/plain, */*',
       'Content-Type': 'application/json'
    },
    body: payload
};

for(var studentID = 0; studentID <= 10; studentID++) {
    fetch(URI, myInit)
    .then( r => r.json() )
    .then( r => console.log(r) 
    .catch(e => console.log(e));
}

studentID 值 (0,1,2,3...) 无法进入 myInit 的 payload 模板。

改用函数。

const makeInit = studentID => ({
    method: 'POST',
    headers: {
       'Accept': 'application/json, text/plain, */*',
       'Content-Type': 'application/json'
    },
    body: `{"studentID": ${studentID}}`
});
for(var studentID = 0; studentID <= 10; studentID++) {
    fetch(URI, makeInit(studentID))

也许不要手动字符串化。

const makeInit = studentID => ({
    method: 'POST',
    headers: {
       'Accept': 'application/json, text/plain, */*',
       'Content-Type': 'application/json'
    },
    body: JSON.stringify({ studentID })
});
for(var studentID = 0; studentID <= 10; studentID++) {
    fetch(URI, makeInit(studentID))