将键数组和值数组合并到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函数会是:
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