2017-07-25 48 views
1

在下面的代碼中,我試圖打印出數組的第一個值(名稱),但它不起作用,如我所料:我只想打印數組中的第一個值(名稱)

function Person (name, age) { 
    this.name = name; 
    this.age = age; 
}// Our Person constructor 


// Now we can make an array of people 
var family = new Array(); 
family[0] = new Person("alice", 40); 
family[1] = new Person("bob", 42); 
family[2] = new Person("michelle", 8); 
family[3] = new Person("timmy", 6); 
// loop through our new array 
for(i = 0; i <= family.Length; i++) { 
    console.log(family[i].this.name); 
} 
+3

'Length'不應該大寫。 – Turnip

+0

循環應該是'我 deceze

+1

您應該使用'family.push(...)'將元素添加到數組中,而不是手動跟蹤索引。 – deceze

回答

0

要想從數組的第一個項目,你可以做下面的無環路:

console.log(family[0].name); 

沒有循環,因爲循環是不必要的,如果你知道你要打印的項目。

或者,如果環是必要的,你可以添加一些邏輯,如

if(i === 0) { 
    console.log(family[0].name); 
} 

訪問陣列中的對象的name屬性時你並不需要使用this

3

您正在錯誤地使用「this」關鍵字。當您訪問family [i]時,您已經在JavaScript中訪問該原型的實例。只要放下「這個」。

-1
function Person (name, age) { 
    this.name = name; 
    this.age = age; 
}// Our Person constructor 


// Now we can make an array of people 
var family = new Array(); 
family[0] = new Person("alice", 40); 
family[1] = new Person("bob", 42); 
family[2] = new Person("michelle", 8); 
family[3] = new Person("timmy", 6); 

// loop through our new array 
for(i = 0; i < family.length; i++) { 
    console.log(family[i].name); 
} 
相關問題