gpt4 book ai didi

Javascript 对象函数不工作

转载 作者:行者123 更新时间:2023-12-03 11:36:58 25 4
gpt4 key购买 nike

我不太确定为什么我的代码运行不正确..我想做的是创建一个杂货列表对象,它有几个用于添加和删除项目的函数..我可以用新项目实例化对象,但我的函数由于某种原因似乎不起作用。如果您能救救我头上剩下的几根头发并告诉我问题出在哪里,我将不胜感激。

            var groceryList = function(itemNames,quantity) {
if (Array.isArray(itemNames)) {
this.items = itemNames;
this.quantity = quantity

this.addItems = function(newItems){
if ( Array.isArray(newItems) ) {
this.items.concat(newItems);
} else {
console.log("Please enter the items in an array fashion!");
};
};

this.removeItem = function(name) {
var listSize = this.items.length;
for (var i = 0; i < listSize; i++) {
if (this.items[i] == name) {
this.items.splice(i,1);
break;
} else {
console.log("Please enter the items in an array fashion!")
};
};
};
} else {
console.log("Please enter the items in an array fashion!")
};
};

最佳答案

.concat() 返回一个新数组,因此您必须将结果分配回实例变量。

所以这个:

this.items.concat(newItems);

需要更改为:

this.items = this.items.concat(newItems);

或者,您实际上可以使用它直接附加到数组:

this.items.push.apply(this.items, newItems);

因为 .push() 可以接受多个参数。

<小时/>

然后,在您的 .removeItem() 函数中,您需要通过更改以下内容来删除实际找到的项目:

this.items.splice(2,1);

对此:

this.items.splice(i,1);

关于Javascript 对象函数不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26446522/

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