2017-03-05 43 views
0

我在這裏考慮了很多主題,考慮到主題,但解決方案似乎不適用於我。我想我有一些邏輯問題。我的代碼非常簡單。我有兩個數組(第一個包含三個字符串和第二個包含三個日期)循環遍歷每次迭代並將其保存到數組中

所有我想要做的就是第一個字符串存儲在一個對象第二陣列中的第一次約會的第一陣列英寸

與所述陣列I中的函數theMainFunc創建(代碼中的問題)的保存3個對象與每個陣列的最後一個索引,而不是匹配他們的像我需要。

下面是代碼:

var dlcNameList = ['they shall not pass', 'in the name of the tsar', 'apocalypse']; 
 
var dlcReleaseDate = [new Date(2017,2,28), new Date(2017,6,15), new Date(2017,11,25)]; 
 

 
function objectCreator (dlcObject,dlcName,dlcDate) { 
 
\t \t dlcObject.name = dlcName; 
 
\t \t dlcObject.date = dlcDate; 
 
\t \t return dlcObject; 
 
} 
 

 
function theMainFunc() { 
 

 
\t var dlcDetails = {}; 
 
\t var i = 0; 
 
\t var storage = []; 
 
\t var x; 
 

 
\t for (i; i <= 2; i++){ 
 
\t x = objectCreator(dlcDetails,dlcNameList[i],dlcReleaseDate[i]); 
 
\t storage[i] = x; 
 
\t } 
 

 
\t return storage; //This returns an array with three "Same" objects. Not what I want to really acheive 
 
} 
 

 
console.log(theMainFunc())

回答

1

在這裏你去(:

注意:您沒有創建新的對象與每次迭代,你可以使用Array#forEach,只需將具有已設置屬性和密鑰的對象推入result陣列即可。

var dlcNameList = ['they shall not pass', 'in the name of the tsar', 'apocalypse'], 
 
    dlcReleaseDate = [new Date(2017,2,28), new Date(2017,6,15), new Date(2017,11,25)], 
 
    result = []; 
 
    
 
    dlcNameList.forEach((v,i) => result.push({name : v, date : dlcReleaseDate[i]})); 
 
    console.log(result);

+0

不知道你的意思是「你不必創建每個迭代的新對象」,爲文本創建一個新的對象,它只是它內聯。 –

+0

@JustinBlank他正在作出新的對象'VAR dlcDetails = {}'與每個迭代**,然後**給它分配的屬性。這基本上不一定在這種情況下。 –

1

因爲dlcDetails在循環上述聲明的,你不小心在重新使用和更新其值,而不是推一個新對象數組。

另請注意,當您使用對象/數組調用函數或將其設置爲另一個對象的屬性的值時,您不會傳遞該對象的副本,而是共享該對象,以便調用者看到對它。你可能會看到這被稱爲「通過參考」,但這有點不恰當。

function theMainFunc() { 
    var storage = []; 

    for (var i = 0; i <= 2; i++){ 
     var dlcDetails = {}; 

     var x = objectCreator(dlcDetails,dlcNameList[i],dlcReleaseDate[i]); 
     storage[i] = x; 
    } 

    return storage; 
} 
0

與您的代碼的問題是,你傳遞給objectCreator()功能相同對象的所有3次(你需要爲你從0開始改變i <= 2i < 2),因此您的存儲剛好有3個相同的引用您的每次調用函數時都會覆蓋屬性的對象。解決方案是在objectCreator()內部創建新對象,而不是將其作爲參數傳遞。

+0

你的意思是直接返回一個對象而不通過它作爲參數? –

+0

是,創建函數內部新的不外 – Max

相關問題