2017-01-07 18 views
-3

我是新来的整个OOP JavaScript风格的编写代码,所以我试图去学习它的潮流。innerHTML不输出任何东西

我写了一个简单的函数,我试图利用原型和this。看起来从动地:

function Person(name, age, height, weight, IQ, ethnicity){ 
    this.fullName = name; 
    this.age = age; 
    this.height = height; 
    this.weight = weight; 
    this.IQ = IQ; 
    this.ethnicity = ethnicity; 
} 

let Jou = new Person("Joseph", 21, 191, 78, 131, "caucasian"); 
let Franc = new Person("Francois", 13, 178, 50, 125, "caucasian"); 
let Svata = new Person("Svatopluk", 61, 188, 85, 140, "caucasian"); 

let names= ["Jou", "Franc", "Svata"]; 
let text = ""; 
for (let i = 0; i < names.lenght; i++){ 
     text += names[i].fullName + " is " + names[i].age + " years old, " 
      + names[i].height + "cm tall, weighs approximately " 
      + names[i].weight + "kg, his IQ is around " + names[i].IQ + 
      " and he belongs to the " + names[i].ethnicity.toUpperCase() + 
      " ethnicity." + "<br>" ; 
} 

document.getElementById("name").innerHTML = text; 

我将其插入:<p id="name"></p>

任何人都可以给我一些指点,对我缺少什么,所以我可以学习如何使用它?

谢谢, Ĵ

+0

继公布答案,我将指出错字:'names.lenght' –

回答

2

names阵列包含字符串,而不是实际的变量。你应该删除双引号。另外,names.lenght应该是names.length

function Person(name, age, height, weight, IQ, ethnicity){ 
 
    this.fullName = name; 
 
    this.age = age; 
 
    this.height = height; 
 
    this.weight = weight; 
 
    this.IQ = IQ; 
 
    this.ethnicity = ethnicity; 
 
} 
 

 
let Jou = new Person("Joseph", 21, 191, 78, 131, "caucasian"); 
 
let Franc = new Person("Francois", 13, 178, 50, 125, "caucasian"); 
 
let Svata = new Person("Svatopluk", 61, 188, 85, 140, "caucasian"); 
 

 
let names= [Jou, Franc, Svata]; 
 
let text = ""; 
 
for (let i = 0; i < names.length; i++){ 
 
     text += names[i].fullName + " is " + names[i].age + " years old, " 
 
      + names[i].height + "cm tall, weighs approximately " 
 
      + names[i].weight + "kg, his IQ is around " + names[i].IQ + 
 
      " and he belongs to the " + names[i].ethnicity.toUpperCase() + 
 
      " ethnicity." + "<br>" ; 
 
} 
 
document.getElementById("name").innerHTML = text;
<div id="name"></div>

0

你在字符串变量封闭名称,而应该引用它们作为变量,而不是字符串,所以更改此:

let names= ["Jou", "Franc", "Svata"]; 

这样:

let names= [Jou, Franc, Svata]; 

此外,你有一个错字,这就是为什么你的原创let names= [Jou, Franc, Svata];没有工作,所以更改

names.lenght 
     ^^^ 

names.length 
     ^^^