gpt4 book ai didi

javascript - array[id].method 不起作用?

转载 作者:行者123 更新时间:2023-12-03 23:22:29 25 4
gpt4 key购买 nike

我有一个 for 循环运行,遍历数组中的每个项目并使用一个方法执行数组项目。由于某种原因,这返回为未定义,但没有 .method 它工作正常。这是我的代码:

    var people = ["susan", "david", "bob", "verity", "rhys", "charles"]

function characters(name, sex) {
this.name = name;
this.sex = sex;
}

var susan = new characters("Susan", "Female");
var david = new characters("David","Male");
var bob = new characters("Bob","Male");
var verity = new characters("Verity","Female");
var rhys = new characters("Rhys","Male");
var charles = new characters("Charles","Male");

characters.prototype.info = function() {
alert("Hi my name is " + this.name + " and I am a " + this.sex);
}


for(i = 0; i < people.length;i++) {
people[i].info();
}

预期的行为是针对每个 Angular 色显示“嗨,我的名字是 [name],我是 [sex]”的警告,但实际上没有任何反应。

最佳答案

你的问题是你的数组是字符串数组而不是 characters 对象数组,这是你的循环所期望的。

people[i] 循环的每次迭代不是您创建的对象,而是包含每个对象的变量名称的字符串。因此,调用您的 info() 方法将不会成功,因为您是在字符串而不是 characters 对象上调用它。

删除引号并重新排列代码,使数组声明位于变量声明之后,这样就可以正常工作:

function characters(name, sex) {
this.name = name;
this.sex = sex;
}

characters.prototype.info = function() {
alert("Hi my name is " + this.name + " and I am a " + this.sex);
}

var susan = new characters("Susan", "Female");
var david = new characters("David", "Male");
var bob = new characters("Bob", "Male");
var verity = new characters("Verity", "Female");
var rhys = new characters("Rhys", "Male");
var charles = new characters("Charles", "Male");

var people = [susan, david, bob, verity, rhys, charles];

for (i = 0; i < people.length; i++) {
people[i].info();
}

关于javascript - array[id].method 不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31235268/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com