# 在 For 循环中创建 JavaScript 数组

2023-03-18 16:21:24

var centres = {

1979: { x: width * 1 / 41, y: height / 2 },

1980: { x: width * 2 / 41, y: height / 2 },

1981: { x: width * 3 / 41, y: height / 2 },

...

}

function nodeYearPos(d) {

return yearCenters[d.year].x;

}

var yearCenters = Array.from(new Array(2020-1919+1), (x, i) => i + 1919);

for (year = 1919; year <= 2020; year++) {

coords = getCentres(year); // this returns an object in the form {x : x, y : y}

yearCenters[year] = coords;

}

## 2 回答

TA贡献1560条经验 获得超1个赞

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贡献1786条经验 获得超12个赞

// 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)

• 2 回答
• 0 关注
• 8 浏览

0/150