2 回答

TA貢獻1780條經(jīng)驗 獲得超1個贊
你可以像 gorak 評論的那樣做,但是使用 getCenters 函數(shù)
var yearCenters = Object.fromEntries(Array.from(new Array(2020-1919+1), (x, i) => [i + 1919, getCenters(i + 1919)]));
或者你也可以試試
var yearCenters = {};
for (year = 1919; year <= 2020; year++) {
coords = getCenters(year);
yearCenters[year] = coords;
}

TA貢獻2012條經(jīng)驗 獲得超12個贊
當(dāng)您嘗試按年份獲取yearCenters數(shù)組(例如yearCenters[year])時,這將不起作用,因為年份不是數(shù)組中的索引。
我建議您首先將數(shù)組轉(zhuǎn)換為 JS 對象,以便對其進行索引可以使用多年。
見下面的片段 -
// Create obejct from array
var yearCenters = Object.fromEntries(Array.from(new Array(2020-1919+1), (x, i) => [i + 1919, null]))
// This loop remains same
for (year = 1919; year <= 2020; year++) {
coords = getCentres(year); // this returns an object in the form {x : x, y : y}
yearCenters[year] = coords;
}
// Mock function
function getCentres(year) {
return {
x: Math.random() * 100,
y: Math.random() * 100
}
}
console.log(yearCenters)
添加回答
舉報