我知道这个问题听起来很愚蠢,但我不知道如何将这个问题变成我想要的。
这是我的代码:
function createPerson() {
var x1 = Math.floor(Math.random()*101); // Random number picker
var personObject = {
primaryNation: primNation(),
secondaryNation: secNation(),
};
function createRandomNation() { //Random nation picker
var nations = ["Germany", "USA", "France"];
var randomNation = nations[Math.floor(Math.random() * nations.length)];
return randomNation;
}
function primNation(){
var randomPrimaryNation = createRandomNation();
return randomPrimaryNation;
}
function secNation() {
var randomSecondaryNation = [];
if (x1 >= "10") {
randomSecondaryNation = createRandomNation();
if (randomSecondaryNation === personObject.primNation){ //// <---There is the problem
randomSecondaryNation = false;
}
}
else {
randomSecondaryNation = false;
}
return randomSecondaryNation;
}
console.log(personObject);
}
问题在于我比较randomSecondaryNation ===(对象,但它没有“完成”定义。
是创建单独对象并将它们分配在一起的唯一方法,还是有更聪明/更快的方法来做到这一点?
谢谢!
答案 0 :(得分:0)
以下是如何组合这两个函数的方法,虽然我仍然不确定为什么randomSecondaryNation作为一个数组开始,然后被赋予一个字符串值,然后有条件地变成一个布尔值。这可能是一个很好的理由,但根据我的经验,这是一个等待发生的错误。无论如何,你走了:
function createPerson() {
var x1 = Math.floor(Math.random()*101); // Random number picker
function createRandomNation() { //Random nation picker
var nations = ["Germany", "USA", "France"];
var randomNation = nations[Math.floor(Math.random() * nations.length)];
return randomNation;
}
function generateNations () {
var randomPrimaryNation = createRandomNation();
var randomSecondaryNation = [];
if (x1 >= "10") {
randomSecondaryNation = createRandomNation();
if (randomSecondaryNation === randomPrimaryNation){
randomSecondaryNation = false;
}
}
else {
randomSecondaryNation = false;
}
return {
primaryNation: randomPrimaryNation,
secondaryNation: randomSecondaryNation
};
}
var personObject = generateNations();
console.log(personObject);
}
createPerson();
createPerson();
createPerson();
&#13;