我正在用 JavaScript 构建一个小型世界构建器(大型模拟的一部分)。
我试图通过为它分配一个函数输出来在构造函数中定义一个对象的属性。
在下面的代码中,“this.identifier”的执行就像一个魅力,但我想为例如“this.gender”分配更复杂的函数。
在“this.gender”中,我想使用 math.random.math.floor 来循环遍历一个数组(有两个值,男性和女性)。
当我编写实际函数时,'this.gender'从新的 Human 对象中删除。
{
"identifier":42,
"lifestate":"Alive",
"health":"100",
"age":"10",
"metabolism":"12",
"econsumption":"11111",
"parent":"yes"
}
我试过使用 return 语句,但没有区别。
class Bluehuman {
constructor() {
this.identifier = Math.floor((Math.random() * 100));
this.lifestate = 'Alive';
this.health = '100';
this.age = '10';
this.metabolism = ['Low','Medium','High'];
this.econsumption = '11111';
this.parent = ['Yes','No'];
this.gender = ['Male','Female']; // Want to change this to a function without dropping from the new Bleuhuman object
}
}
var bluehuman = {};
var bluehumans = [];
for (var i = 0; i < 10; i++) {
bluehuman[i] = new Bluehuman();
bluehumans.push(bluehuman[i]);
}
var arrayPrint = JSON.stringify(bluehumans);
console.log(arrayPrint)
如何将函数的输出分配给 'this.gender' 而不会从新的 bluehuman 对象中删除它?
你不需要一个函数,一个表达式就可以解决你的问题
class Bluehuman {
constructor() {
this.identifier = Math.floor((Math.random() * 100));
this.lifestate = 'Alive';
this.health = '100';
this.age = '10';
this.metabolism = ['Low','Medium','High'];
this.econsumption = '11111';
this.parent = ['Yes','No'];
this.gender = ['Male','Female'][Math.round(Math.random())];
}
}
var bluehuman = {};
var bluehumans = [];
for (var i = 0; i < 10; i++) {
bluehuman[i] = new Bluehuman();
bluehumans.push(bluehuman[i]);
}
var arrayPrint = JSON.stringify(bluehumans);
console.log(arrayPrint)
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句