这是我的代码。
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
}
当前的输出仅为collatedArray [i] .test1,它提供:
4, 7, 3, 2
如果将output [i] = collatedArray [i] .test1更改为test2,则会得到:
d, a, b, c
我只想输出整个collatedArray(test1和test2),以便得到:
4, 7, 3, 2
d, a, b, c
无需输出变量或转换回数组。这些信息就在那里,我只是想不出办法。编码非常新,只是不了解在这里做什么:(
谢谢
最佳答案
将output
调整为包含两个数组的数组;最后一个for
循环中的output
和collatedArray[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())