将两个数组中的元素组合到第三个数组中
Combine elements from two arrays into subarrays in a third array
我从两个等长数组开始,我想创建一个由子数组组成的新数组,每个子数组都是由两个数组的每个索引处的元素组合而成的。我的意思是:
// the 2 initial arrays:
var arr1 = ["Quote1", "Quote2", "Quote3"];
var arr2 = ["Author1", "Author2", "Author3"];
// the output I need to achieve:
[ ["Quote1", "Author1"], ["Quote2", "Author2"], ["Quote3", "Author3"] ];
问题是我的代码向console.log
:产生以下输出
Array [ Array[2], Array[2], Array[2] ]
我得到的有问题的输出没有显示每个子数组的实际值,它只显示每个子阵列的长度。
这是我的代码:
var quotesArr = ["Quote 1", "Quote 2", "Quote 3"];
var authorsArr = ["Author 1", "Author 2", "Author 3"];
var quoteMeetsAuthor = [];
var quotesAndAuthors = [];
function combineArrays(quotes,authors) {
if (quotes.length != authors.length) {
console.log("Danger Will Robinson!");
return "Danger Will Robinson!";
}
for (i=0; i<quotes.length; i++) {
quoteMeetsAuthor.push(quotes[i]);
quoteMeetsAuthor.push(authors[i]);
quotesAndAuthors.push(quoteMeetsAuthor);
quoteMeetsAuthor = [];
}
console.log(quotesAndAuthors);
return quotesAndAuthors;
}
combineArrays(quotesArr, authorsArr);
有人能提供建议吗?
编辑:我想使用普通javascript来解决这个问题。
以下是我为解决您的问题而想出的方法。此外,请尝试使用alert()而不是console.log()来查看真实结果。console.log()有时不会显示所有内容,因此您需要扩展它存储的内容:
var arr1 = ["Quote1", "Quote2", "Quote3"];
var arr2 = ["Author1", "Author2", "Author3"];
// the output I need to achieve:
//[ ["Quote1", "Author1"], ["Quote2", "Author2"], ["Quote3", "Author3"] ];
var newArr = [[],[],[]];
for(var i = 0; i < newArr.length; i++){
newArr[i].push(arr1[i]);
newArr[i].push(arr2[i]);
}
alert(newArr);
相关文章:
- 根据id将json数组组合为一个json数组
- jqueryeasyui使用子数组组合数据
- javascript数组中条目的成对组合
- 将数组中的所有数字组合相加
- JavaScript算法,提供每种可能的项目组合,并将它们存储在数组中
- 将两个数组合并为一个具有键值关系的数组
- 如何将数组的对象与同一索引组合
- 将对象隐藏到组合/对象数组
- 将数组组合到一个对象中
- D3.js键功能在简单的选择器/数组组合上运行两次
- 如何将两个 JSON 数组组合在一个 JSON 数组中
- 将JSON数组的一部分与另一个JSON数组组合在一起
- 如何将具有相同键的对象数组组合为一个对象
- Javascript数组组合变量值
- 数组组合以解决遍历问题
- Javascript中的循环函数在与perl数组组合时失败
- 使用javascript将一个对象数组组合为一个
- angarjs / javascript将两个长度相同的数组组合在一起
- 返回数组组合的数组的函数
- 如何使用ng中的if条件重复,并在ng选项中显示数组组合删除重复项