如何将数组转换为对象

Kat*_*ler 1 javascript arrays object

我正在尝试从半径和 x,y 坐标制作一个圆。除了数组不是我使用的正确格式之外,我已经完成了所有操作。我得到:

[
    "X_PROPS:40,Y_PROPS:0",
    "X_PROPS:39.99390780625565,Y_PROPS:0.6980962574913405",
    "X_PROPS:39.97563308076383,Y_PROPS:1.3959798681000388",
    "X_PROPS:39.94518139018295,Y_PROPS:2.093438249717753"
]
Run Code Online (Sandbox Code Playgroud)

但是我需要:

[
    {X_PROPS:40,Y_PROPS:0},
    {X_PROPS:39.99390780625565,Y_PROPS:0.6980962574913405},
    {X_PROPS:39.97563308076383,Y_PROPS:1.3959798681000388},
    {X_PROPS:39.94518139018295,Y_PROPS:2.093438249717753}
]
Run Code Online (Sandbox Code Playgroud)

我试过这个:

function spec(radius, steps, centerX, centerY){
  var xValues = [centerX];
  var yValues = [centerY];
  var result = [];
  for (var i = 0; i < steps; i++) {
    xValues[i] = (centerX + radius * Math.cos(2 * Math.PI * i / steps));
    yValues[i] = (centerY + radius * Math.sin(2 * Math.PI * i / steps));

    result.push('X_PROPS:'+ xValues[i]+','+'Y_PROPS:'+ yValues[i]);
  }

  return result;

}
console.log(spec(40,360,0,0))
Run Code Online (Sandbox Code Playgroud)

Ori*_*ori 5

此表达式'X_PROPS:'+ xValues[i]+','+'Y_PROPS:'+ yValues[i]创建一个字符串。改为创建一个对象字面量:

function spec(radius, steps, centerX, centerY) {
  var result = [];
  for (var i = 0; i < steps; i++) {
    result.push({
      X_PROPS: (centerX + radius * Math.cos(2 * Math.PI * i / steps)),
      Y_PROPS: (centerY + radius * Math.sin(2 * Math.PI * i / steps))
    });
  }

  return result;

}
console.log(spec(40, 360, 0, 0))
Run Code Online (Sandbox Code Playgroud)