javascript - 在 Javascript 中组合数组

标签 javascript arrays

也许现在在德国太晚了(凌晨 1:04)或者我错过了什么......

如何组合这两个数组:

a = [1, 2, 3] and b = [a, b, c] so that i get: [[1, a], [2, b], [3, c]]

谢谢...花更多的时间 sleep ! :)

编辑:

我看到这个函数叫做“zip”。 +1 知识

并且在 JavaScript 中没有内置函数用于此。 +1 知识

我应该说数组的长度是相等的。 -1知识

最佳答案

Array.prototype.zip = function(other) {
    if (!Array.prototype.isPrototypeOf(other)) {
         // Are you lenient?
         // return [];
         // or strict?
         throw new TypeError('Expecting an array dummy!');
    }
    if (this.length !== other.length) {
         // Do you care if some undefined values
         // make it into the result?
         throw new Error('Must be the same length!');
    }
    var r = [];
    for (var i = 0, length = this.length; i < length; i++) {
        r.push([this[i], other[i]]);    
    }
    return r;
}

关于javascript - 在 Javascript 中组合数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5207665/

相关文章:

javascript - 为什么这个正则表达式模式没有传入 exec 方法?

javascript - 采用一个或一组对象的 Typescript 函数

java - 稳定排序java按字母顺序排列数组

C 动态分配的数组未正确传递

c++ - Array + int 作为一个参数有什么作用?

javascript - 匹配出现在表格单元格行首的单词

javascript - 如何使用 Javascript 截取 GMaps Frame 的屏幕截图并将其转换为图像?

javascript - Extjs4 MVC 将项目保存到服务器

javascript - 使用一些数组元素连接字符串 (Javascript)

java - 如何在android中为固定的IMEI生成固定的字节数组