在 JavaScript 中将键数组和值数组合并到一个对象中
问题描述:
我有:
var keys = [ "height", "width" ];
var values = [ "12px", "24px" ];
我想把它转换成这个对象:
And I'd like to convert it into this object:
{ height: "12px", width: "24px" }
在 Python 中,有一个简单的习惯用法 dict(zip(keys,values))
.jQuery 或纯 JavaScript 中是否有类似的东西,或者我必须长期这样做?
In Python, there's the simple idiom dict(zip(keys,values))
. Is there something similar in jQuery or plain JavaScript, or do I have to do this the long way?
答
简单的 JS 函数应该是:
Simple JS function would be:
function toObject(names, values) {
var result = {};
for (var i = 0; i < names.length; i++)
result[names[i]] = values[i];
return result;
}
当然你也可以实际实现像 zip 等函数,因为 JS 支持更高阶的类型,这使得这些函数式语言主义很容易 :D
Of course you could also actually implement functions like zip, etc as JS supports higher order types which make these functional-language-isms easy :D