gpt4 book ai didi

javascript - 函数不会推送到空数组来创建列表。如何解决这个问题

转载 作者:行者123 更新时间:2023-11-30 11:05:42 26 4
gpt4 key购买 nike

我正在尝试通过函数调用将项目添加到爱好列表中。但它没有添加,我一直在得到空数组。我想念一些愚蠢的东西。你能指导我解决这个问题吗?我包括我正在处理的所有代码。

我试过像这样调用函数。person().addHobby('TestHobby');


function person(firstName, lastName) {

var FullName = firstName + ' ' + lastName;
var hobbies = [‘’];

return {

/**
* Returns truthy if the person already has this hobby
* @param {string} hobby
* @returns {boolean}
*/
hasHobby: function(hobby) {
return hobbies.indexOf(hobby)>=0;
},

/**
* Returns the person's hobbies after adding the given hobby
* @param {string} hobby
* @returns {array}
*/
addHobby: function(hobby) {
return hobbies.indexOf(hobby)>0 ? hobbies : hobbies.push(hobby);
},

/**
* Returns the person's hobbies after removing the given hobby
* @param {string} hobby
* @returns {array}
*/
removeHobby: function(hobby) {
if (hobbies.indexOf(hobby)>0) {
// note: filter is a standard array function that creates a new array
// with all elements that pass the test implemented by the provided function
hobbies = hobbies.filter(function(hobby) {
return hobby != hobby;
});
return hobbies;
} else {
return hobbies;
}
},

/**
* Returns the person's hobbies
* @returns {array}
*/
getHobbies: function() {
return hobbies
},

/**
* Returns the person's full name
* @returns {string}
*/
getName: function() {
return FullName;
},

};
};

最佳答案

也许您不确定您在这里实际创建了什么。这是人的类定义。要调用它的方法,您需要创建一个新的 person 实例,例如:

var gregory=new person();

gregory 是您对新创建的人的引用。给格雷戈里一个爱好:

gregory.addHobby("sleeping");

现在您可以查询他的爱好,例如:

console.log(gregory.getHobbies());

关于javascript - 函数不会推送到空数组来创建列表。如何解决这个问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55714735/

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