2017-01-07 143 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 
     ^^^