2016-10-30 170 views
1

说我有两个数组坐在一个对象内,并且有一个函数可以从用户指定的数组中删除一个项目。如何从多个阵列中删除?

var warehouse{ 
    shirts: [], 
    shorts: [], 

    deleteItem: function(itemType, itemNumber){ 
    this.itemType.splice(itemNumber, 1); 
    } 
} 

所以,如果我这样做:

function('shirts', 0); 

应该的 '衬衫' 数组中删除的第一个项目。问题是,它告诉我,ITEMTYPE快到了为undefined

+0

你的语法是关闭的 - '变种仓库= {'和'仓库.deleteItem('衬衫',0);',对于初学者。除此之外,当你试图使用一个变量作为这样的数组键时,试试'this [itemType]'而不是'this.itemType'。 – jack

回答

6

你应该使用bracket notation

var warehouse = { 
 
    shirts: [1, 2, 3, 4], 
 
    shorts: [1, 2, 3, 4], 
 
    deleteItem: function(itemType, itemNumber){ 
 
    this[itemType].splice(itemNumber, 1); 
 
    } 
 
}; 
 

 
warehouse.deleteItem("shirts", 0); 
 
console.log(warehouse);