在 For 循环中创建 JavaScript 数组

我想用 for 循环创建下面的数组作为它的大


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;

  }


慕仙森
浏览 89回答 2
2回答

慕神8447489

你可以像 gorak 评论的那样做,但是使用 getCenters 函数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++) {&nbsp; coords = getCenters(year);&nbsp; yearCenters[year] = coords;}

繁花如伊

当您尝试按年份获取yearCenters数组(例如yearCenters[year])时,这将不起作用,因为年份不是数组中的索引。我建议您首先将数组转换为 JS 对象,以便对其进行索引可以使用多年。见下面的片段 -// Create obejct from arrayvar yearCenters = Object.fromEntries(Array.from(new Array(2020-1919+1), (x, i) => [i + 1919, null]))&nbsp; &nbsp; &nbsp;// This loop remains samefor (year = 1919; year <= 2020; year++) {&nbsp; &nbsp; coords = getCentres(year); // this returns an object in the form {x : x, y : y}&nbsp; &nbsp; yearCenters[year] = coords;&nbsp;}// Mock functionfunction getCentres(year) {&nbsp; return {&nbsp; &nbsp; x: Math.random() * 100,&nbsp; &nbsp; y: Math.random() * 100&nbsp; }}console.log(yearCenters)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript