Javascript对象功能不起作用

时间:2014-10-19 01:59:09

标签: javascript

我不确定为什么我的代码运行不正确..我要做的是创建一个购物清单对象,它有几个功能来添加和删除项目.. 我可以使用新项目实例化对象,但由于某些原因,我的功能似乎不起作用。 如果你能省下我头上留下的几根头发并告诉我问题在哪里,我会非常感激。

            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!")
                };
            };

1 个答案:

答案 0 :(得分:1)

.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);