Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/136.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在For循环中创建JavaScript数组_Javascript - Fatal编程技术网

在For循环中创建JavaScript数组

在For循环中创建JavaScript数组,javascript,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 yea

我想在下面创建一个数组,其中一个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;
  }
var yearCenters=Array.from(新数组(2020-1919+1),(x,i)=>i+1919);

对于(year=1919;year,您可以按照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++) {
  coords = getCenters(year);
  yearCenters[year] = coords;
}
var yearCenters={};

对于(year=1919;year当您尝试在
yearCenters
数组中按年份获取时(例如
yearCenters[year]
),这将不起作用,因为年份不是数组中的索引

我建议您首先将数组转换为JS对象,以便对其进行索引可以使用多年

请参阅下面的代码片段-

//从数组创建obejct
var yearCenters=Object.fromEntries(数组.from(新数组(2020-1919+1),(x,i)=>[i+1919,null]))
//这个循环保持不变

对于(year=1919;year使用对象,而不是数组。数组是0索引的
yearCenters=object.fromEntries(array.from)(新数组(2020-1919+1),(x,i)=>[i+1919,null]);
将数组转换为对象,然后设置值。我使用了后一种建议,因为它创建了一个空对象({}),这很好而且很清晰然后填充它。