1

标签(空格分隔): 未分类

问题:有两个数组 分别是:

1.["a","b","c"]

2.["1","2","3"]

上面两个数组合并

形成3.["a","1","b","2","c","3"]

上代码

            var arr1 = ["a", "b", "c"];
            var arr2 = ["1", "2", "3"];
            var arr3 = [], 
            len = arr1.length;
            for (i = 0; i < len; i++) {
    // arr3.splice(len.length - 1, 0, arr1[i], arr2[i]);
                arr3.push(arr1[i]);
                arr3.push(arr2[i]);
            }
            console.log(arr3)

如果要给初始两个数组添加数据可以将上面代码转变为一个函数

function newArr(new1, new2) {
            var arr1 = ["a", "b", "c"];
            arr1.push(new1);
            var arr2 = ["1", "2", "3"];
            arr2.push(new2);
            var arr3 = [], len = arr1.length;
            for (i = 0; i < len; i++) {
    // arr3.splice(len.length - 1, 0, arr1[i], arr2[i]);
                arr3.push(arr1[i]);
                arr3.push(arr2[i]);
            }
            return arr3;
        }
        var ne = newArr("aAne", "cTwo");
        console.log(ne);

简洁法:

    function newArr(arr1, arr2) { //定义一个函数,传两个参数 arr1第一数组,arr2是第二个数组
                var kong = []; //声明一个空数组,来放交叉拼接后的数组
                for (var i = 0, l = arr1.length; i < l; i++) {
                    // kong.splice(kong.length,0,arr1[i],arr2[i]);   
                    //数组里的索引从0开始,kong从1开始,0是要删除的个数 
                    kong.push(arr1[i]);
                    //console.log(kong);  //a
                    kong.push(arr2[i]);
                    //console.log(kong); //a 1
                }
                return kong;
            }
            var arr = newArr(["a", "b", "c", "e"], ["1", "2", "3", "4"]);

document.write(arr + '<br/>');

酷酷的long
27 声望2 粉丝