javascript - jquery 将两个数组(键,值)关联成一个数组

标签 javascript jquery arrays associations mootools

如何将包含键和值的两个数组关联到一个具有键->值对的数组中?

在 Mootools 中有一个 associate 函数,它可以:

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
sounds.associate(animals);
// returns {'Cow': 'Moo', 'Pig': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'}

JQuery 中是否有任何类似的函数可以从这两个数组中获取相同的结果?

如果不行,我该怎么做?

最佳答案

JavaScript 并没有真正的关联数组,但您可以使用对象代替。

Array.prototype.associate = function (keys) {
  var result = {};

  this.forEach(function (el, i) {
    result[keys[i]] = el;
  });

  return result;
};

var animals = ['Cow', 'Pig', 'Dog', 'Cat'];
var sounds = ['Moo', 'Oink', 'Woof', 'Miao'];
console.dir(sounds.associate(animals));

关于javascript - jquery 将两个数组(键,值)关联成一个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23908283/

相关文章:

jquery - iPad jQuery 菜单,单击外部任意位置可隐藏下拉菜单

.net - Array.Copy 与 Buffer.BlockCopy

c# - 使用 JQuery 和 Cookie 插件创建一个非 url 编码值的 cookie

javascript - 在 HTML 中选择图像

jquery - IE<v9问题,标签中的jquery UI单选按钮img不会触发值更改

javascript - 我在页面加载时将整个 $_SESSION 变量放入 json 对象中。虽然这对我有用,但这是一个好的做法吗?

arrays - 对数组元素的地址进行减法时出现意外结果

c++ - 关于c++中遍历数组的问题

javascript - 将数据保存到使用 Ajax 以 JSON 形式发送的文本文件中

javascript - React 和 Firebase : adding date to database causes listener to trigger twice?