这是我的代码。

function order() {

  //declare things
var order = [3, 2, 1, 0]
var testOne = [2, 3, 7, 4]
var testTwo = ["c", "b", "a", "d"]


//sort by order
  var collatedArray = [];
    for (var i = 0; i < order.length; i++)
    {
        index = order[i];
        var collated =
        {
           test1 : testOne[index],
           test2 : testTwo[index]
        }
        collatedArray.push(collated);
    }


  //Create output
  var output = [];
  for (i=0; i<collatedArray.length; i++)
  {
    output[i] = collatedArray[i].test1
  }

return output
}


当前的输出仅为collat​​edArray [i] .test1,它提供:

4, 7, 3, 2


如果将output [i] = collat​​edArray [i] .test1更改为test2,则会得到:

d, a, b, c


我只想输出整个collat​​edArray(test1和test2),以便得到:

4, 7, 3, 2
d, a, b, c


无需输出变量或转换回数组。这些信息就在那里,我只是想不出办法。编码非常新,只是不了解在这里做什么:(
谢谢

最佳答案

output调整为包含两个数组的数组;最后一个for循环中的outputcollatedArray[0][i].test1值填充collatedArray[1][i].test2中的每个数组

  // Create output
  var output = [[], []];
  for (i=0; i<collatedArray.length; i++)
  {
    output[0][i] = collatedArray[i].test1;
    output[1][i] = collatedArray[i].test2;
  }






function order() {

  //declare things
  var order = [3, 2, 1, 0]
  var testOne = [2, 3, 7, 4]
  var testTwo = ["c", "b", "a", "d"]


  //sort by order
  var collatedArray = [];
  for (var i = 0; i < order.length; i++) {
    index = order[i];
    var collated = {
      test1: testOne[index],
      test2: testTwo[index]
    }
    collatedArray.push(collated);
  }


  //Create output
  var output = [
    [],
    []
  ];
  for (i = 0; i < collatedArray.length; i++) {
    output[0][i] = collatedArray[i].test1;
    output[1][i] = collatedArray[i].test2;
  }

  return output
}

console.log(order())

10-07 16:36