【发布时间】:2019-05-02 15:32:50
【问题描述】:
我正在用 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"
}
- gender 在我将其更改为函数时被删除。
我尝试过使用 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 对象中删除?
【问题讨论】:
-
这应该不是问题。您应该显示不起作用的代码。
-
JSON 不能包含函数。
-
@JonasWilms,听起来 OP 想要一个函数的 result,比如
this.identifier:How can I assign the output of a function... -
能否请您添加不起作用的代码(与功能)?
-
感谢所有 cmets Jonas 和 Mark。真的很感激。下面@DanyalImran 的评论解决了我的问题:-)
标签: javascript arrays object constructor