javaScript中支持多繼承,通過this關鍵字實現多繼承. 下面這個例子是來判斷父母結合后,隨機產生子女
//下面探討的問題是 父母結合后子女的性別
function father(){
this.DNA1 = 'X';
this.DNA2 = 'Y';
//存儲father中所有的染色體的數組
this.arrayF = [this.DNA1,this.DNA2];
this.sex = function(){
this.DNA = this.DNA1+" " +this.DNA2;
//console.log('this is a man');
}
}
function mother(){
this.DNA1 = 'X';
this.DNA2 = 'X';
//存儲mother中所有的染色體的數組
this.arrayM = [this.DNA1,this.DNA2];
this.sex = function(){
this.DNA= this.DNA1+" " +this.DNA2;
//console.log('this is a woman');
}
}
//定義全局變量,統計出現的次數,
var count = 0;
var count1 = 0;
var count2 = 0;
function children(){
this.mother = mother;
this.father = father;
//從father中隨機取出一條染色體
this.DNA1 = this.arrayF[Math.floor(Math.random()*(this.arrayF.length)+1)-1];
//從mother中隨機取出一條染色體
this.DNA2 = this.arrayM[Math.floor(Math.random()*(this.arrayM.length)+1)-1];
//如果是男孩
if(this.DNA1 !== this.DNA2){
count1++;
this.sex="The baby is a boy"
}else{
count2++;
this.sex="The baby is a girl"
}
count++;
console.log(this.sex);
};
//測試函數
function test(label){
for(var i=0;i<label;i++){
children();
console.log('男孩出現的次數為: '+count1+"\n"+'女孩出現的次數為: '+count2+"\n"+"總次數為: "+count);
}
}
//test(10);
通过JavaScript实现了一个简单的遗传算法模拟,该模拟展示了如何通过随机选择父母的基因来决定孩子的性别,以此来模拟遗传过程。
1276

被折叠的 条评论
为什么被折叠?



