2014-10-19 158 views
0

我不太确定为什么我的代码运行不正确..我想要做的是创建一个购物清单对象,它有几个函数来添加和删除项目.. 我可以实例化新项目的对象,但我的功能似乎不工作的原因。 如果你能救我头脑里剩下的几根头发,并告诉我问题在哪里,我将不胜感激。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!") 
       }; 
      }; 
+0

[ “CONCAT” 的可能重复不加入JavaScript数组?](http://stackoverflow.com/questions/12810366/concat-does-not-join-javascript-arrays-together) – 2014-10-19 05:55:52

回答

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); 
+0

“因为.push()可以采用多个参数。” - whaaaaaat!你每周都会学到新东西! – Rudie 2014-10-19 02:16:21

+0

非常感谢!我试图使用'concat()'认为它的功能与'push()'类似,但你的解释很明显。 – WebAhmed 2014-10-19 06:00:50