2014-12-04 40 views
-2

在此先感謝,如果數組jQuery的助理兩個數組(鍵,值)到一個數組複製的鑰匙

var animals = ['Cow', 'Cow', 'Dog', 'Cat']; 
var sounds = ['Moo', 'Oink', 'Woof', 'Miao']; 

我怎樣才能得到一個assoc命令陣列這樣

// returns {'Cow': 'Moo', 'Cow': 'Oink', 'Dog': 'Woof', 'Cat': 'Miao'} 
+2

你的意思是 「豬」,爲第二個 「牛」,對不對?你不能有一個對象有兩個相同的鍵。 – 2014-12-04 13:57:54

+0

如何?編寫一個算法並對其進行編碼。這裏沒有人會爲你編碼。這不是SO的目的。 – melancia 2014-12-04 13:58:18

回答

1

JS提琴所有3個選項中的一個:http://jsfiddle.net/ysLvfxmd/2/

您想要一個散列/關聯數組,循環遍歷並通過索引創建一個數組,但是您不能在散列中有重複鍵,因此您可能需要探索ot她的數據結構。

純哈希

var animals = ['Cow', 'Cow', 'Dog', 'Cat']; 
var sounds = ['Moo', 'Oink', 'Woof', 'Miao']; 
var hash = {}; 

for(i = 0; i < animals.length; i++) { 
    hash[animals[i]] = sounds[i]; 
} 

console.log(hash); 

,如果你想擁有對這個有你需要做散列的數組

陣列的非唯一鍵這將只顯示牛一次,哈希

var animals = ['Cow', 'Cow', 'Dog', 'Cat']; 
var sounds = ['Moo', 'Oink', 'Woof', 'Miao']; 
var arr = []; 

for(i = 0; i < animals.length; i++) { 
    var hash = {}; 
    hash[animals[i]] = sounds[i]; 
    arr.push(hash); 
} 

console.log(arr); 

但是請注意,數組的索引現在是數字bu你可以通過搜索找到你的價值觀。

第三個選擇:

哈希陣列(最佳)

//Paul Rob's suggestion hash of arrays 

var animals = ['Cow', 'Cow', 'Dog', 'Cat']; 
var sounds = ['Moo', 'Oink', 'Woof', 'Miao']; 
var hashOfArr = []; 

for(i = 0; i < animals.length; i++) { 
    if(!hashOfArr[animals[i]]){ 
     hashOfArr[animals[i]] = []; 
    } 
    hashOfArr[animals[i]].push(sounds[i]); 
} 
console.log(hashOfArr); 
+0

似乎更理智地使用數組散列,例如''''牛':['Moo','Oink'],'狗':['Woof'],'Cat':['Miao']} – 2014-12-04 14:17:34

+0

我在寫完之後想到了同樣的事情,我爲此增加了另一個例子 – 2014-12-04 14:19:08

0

簡短的回答

你到底想要什麼是不可能的。對象不能有多個鍵。

我的建議

有一個對象,其中每個鍵的值是一個數組。如果動物有多種聲音,只需將其推入陣列即可。

var 
animals = ['Cow', 'Cow', 'Dog', 'Cat'], 
sounds = ['Moo', 'Oink', 'Woof', 'Miao'], 
result = {}; 

for(i = 0; i < animals.length; i++) { 
    result[animals[i]] 
     ? result[animals[i]].push(sounds[i]) 
     : result[animals[i]] = [sounds[i]]; 
} 

Fiddle

相關問題