使用JavaScript根据索引合并多个数组 [英] Merge multiple arrays based on their index using javascript

查看:138
本文介绍了使用JavaScript根据索引合并多个数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将两个数组合并为一个数组。我有代码,但是没有按预期工作-它将它们一个接一个地合并,但是我需要互锁值。

I need to merge two arrays into a single array. I have code but it is not working as expected-- it is merging them one after another, but I need to interlock the values.

<html>

<head>
    <title></title>
    <script src="https://code.jquery.com/jquery-3.1.1.js"></script>
</head>

<body>
    <div id="result"></div>
    <script type="text/javascript">
    var array1 = [1, 2, 3, 4];
    var array2 = ["a", "b", "c", "d"];
    var newArray = $.merge(array1, array2);
    $("#result").html(newArray);
    //the result its 1234absd
    //ineed result like 1a,2b,3c,4d
    </script>
</body>

</html>

推荐答案

您可以在 Array#map 中使用普通的javascript。

You can use Array#map in plain javascript.

var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];

var newArray = array1.map((e, i) => e + array2[i]);
console.log(newArray);

如果在array1上使用map,则第一个参数为当前参数循环中array1的值,第二个参数是该元素在数组中的索引。因此,您可以使用index将array1中的当前元素与其他具有相同索引的数组中的元素进行匹配。

If you use map on array1 then first parameter is current value of array1 in loop and the second parameter is index of that element in array. So you can match current element in array1 with elements from other arrays with the same index using index.

var array1 = [1, 2, 3, 4];
var array2 = ["a", "b", "c", "d"];
var array3 = ["f", "d", "s", "a"];

var newArray = array1.map(function(value, index) {
  return value + array2[index] + array3[index];
});
console.log(newArray);

这篇关于使用JavaScript根据索引合并多个数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆