Rumah > Soal Jawab > teks badan
这里有两个数组,分别为
var arr1 = [5, 6, 7, 8, 9];
var arr2 = ['a', 'b', 'c', 'd', 'e'];
能否以arr1为key,arr2为value合并成新的数组对象呢?
最终效果为
{ 5:'a', 6:'b', 7:'c', 8:'d', 9:'e'}
谢谢。
ringa_lee2017-04-10 13:12:22
如果没有重复的话:
var arr1 = [5, 6, 7, 8, 9];
var arr2 = ['a', 'b', 'c', 'd', 'e'];
var obj = {} ;
for(var i=0; i< arr1.length; i++){
obj[arr1[i]] = arr2[i] ;
}
console.log(obj);
/*输出*/
Object {5: "a", 6: "b", 7: "c", 8: "d", 9: "e"}
阿神2017-04-10 13:12:22
@沙渺 使用的underscore.js
的确有这个函数,但不是_.zip()
,而是_.object()
:
<script src="http://underscorejs.org/underscore-min.js"></script>
<script>
var arr1 = [5, 6, 7, 8, 9];
var arr2 = ['a', 'b', 'c', 'd', 'e'];
console.log( _.object(arr1, arr2) );
</script>
Object {5: "a", 6: "b", 7: "c", 8: "d", 9: "e"}