我一直在尋找了一段時間,似乎無法找到一個答案,我面臨的問題中的對象的值。我是新來的,所以我有一個相當高的機會,我只是在做我想做錯的事情。我所做的目的只是爲了瞭解我能做什麼,不能做什麼對象,數組和循環,所以當我用我想要做的事來完成這個項目時,我正在慢慢地想出如何去做這些東西。訪問鍵和對象
所以我這裏有一堆的對象(與鍵和值)。我將把這些單獨的(Character)對象存儲到另一個名爲Characters的對象中。
function Character(sociability, assertiveness, adventurous, emotionalExpressiveness, kindness, altruism, affection, trust, impulseControl, thoughtfullness, emotionalStability, sexuality, evil, intellectualCuriosity, novelty, interests, intelligence) {
"use strict";
this.sociability = sociability;
this.assertiveness = assertiveness;
this.adventurous = adventurous;
this.emotionalExpressiveness = emotionalExpressiveness;
this.kindness = kindness;
this.altruism = altruism;
this.affection = affection;
this.trust = trust;
this.impulseControl = impulseControl;
this.thoughtfullness = thoughtfullness;
this.emotionalStability = emotionalStability;
this.sexuality = sexuality;
this.evil = evil;
this.intellectualCuriosity = intellectualCuriosity;
this.novelty = novelty;
this.interests = interests;
this.intelligence = intelligence;
}
var aloy = new Character(0, 11, 11, 0, 11, 11, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0),
bayonetta = new Character(0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 13, 14, 17, 0, 11, 0, 0),
elizabeth = new Character(0, 0, 0, 0, 11, 0, 0, 0, 0, 0, 0, 0, 0, 12, 12, 12, 12),
ellie = new Character(0, 12, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 11, 10),
//store all above objects into new object
var Users = {
aloy: aloy,
bayonetta: bayonetta,
elizabeth: elizabeth,
ellie: ellie,
};
在此之後我創建包括從Character對象鍵的5名數組:
var matchArr = ["sociability", "assertiveness", "adventurous", "emotionalExpressiveness", "kindness"]
下面是我卡在一部分,我會試着解釋盡我所能。我會先告訴你代碼,然後嘗試理解我想要做的事情。
for (i = 0; i <= 4; i++) {
for (var obj in Users) {
if (Users.obj.matchArr[0] > 1) {
console.log(obj)
}
}
}
我想要做的是遍歷Users
對象,如果對象(Characters
)內的對象之一具有與滿足我的if
語句價值的關鍵,登錄該字符對象的名稱。
- 如果我登錄for (var obj in Users) { console.log(obj); }
我按照預期循環存儲在Users
中的每個Character
名稱。
- 如果我通過itslef登錄matchArr[0]
我得到"sociability"
從我matchArr
陣列的預期。
- 如果我登錄Users.aloy.sociability
我得到0
如預期它的aloy.sociability
價值 - 但是,如果我登錄Characters.aloy.matchArr[0]
我得到一個錯誤(無法未定義讀取屬性「0」)。我不明白爲什麼這是不是明確打字sociability
因爲這是matchArr[0]
精確值不同。
我如何正確引用Users.aloy.sociability
例如以我試圖的方式。在我的腦海中,當我參考Users.obj.matchArr[0]
時,這與明確鍵入Users.aloy.sociability
,Users.bayonetta.sociability`(等等,因爲它循環)相同。
再說一次,我可能會對這個完全錯誤的事情進行討論,即使它只是指向其他文檔,我可以通讀並獲得更好的理解,這可能會使我朝着正確的方向發展,但我會感激任何幫助。
我唯一的猜測是數組值(例如matchArr[0] > "sociability"
)是一個字符串,我不能以這種方式使用字符串。如果是這樣,我不知道該怎麼辦。
非常感謝您的幫助。
請縮短您的代碼示例。你只需要幾個有幾個屬性的字符來說明你的問題。 –