[英]Delete item in array from item?
req.user.hails[0]
is an instance of the class hails, it has the method cancel()
I call it like this: req.user.hails[0]
是冰雹类的实例,它具有方法cancel()
我这样称呼它:
req.user.hails[0].cancel()
Can I from inside that instance remove the item itself? 我可以从该实例内部删除项目本身吗?
cancel: function() {
//this will remove the item from a databae
this.destroy()
//Here I want to delete "this".
}
The desired result is that req.user.hails.length
is one shorter than before. 理想的结果是req.user.hails.length
比以前短一。 I know I can remove it from where I'm calling cancel. 我知道我可以从调用取消的位置将其删除。
No, you can't, not unless it happens (which is unlikely) that cancel
closes over req
, req.user
, or req.user.hails
. 不,您不能,除非发生这种情况(这不太可能),否则cancel
关闭req
, req.user
或req.user.hails
。 (And even then, it would be a really dodgy thing to do.) If it doesn't there's no information provided to your method that you can use to remove the entry from the array. (即使那样,也确实是一件很狡猾的事情。)如果没有,则没有任何信息可用于从数组中删除条目。
You could add a method to hails
that both does the cancellation and removes the entry: 您可以在hails
中添加一个既可以取消也可以删除条目的方法:
req.user.hails.cancelEntry = function(index) {
this[index].cancel();
this.splice(index, 1);
};
Yes, you can really add non-index properties to arrays like that. 是的,您真的可以像这样向数组添加非索引属性。 Note that they'll be enumerable, which is one reason not to use for-in
loops to loop through arrays. 请注意,它们将是可枚举的,这是不使用for-in
循环遍历数组的原因之一。 (More about looping arrays in this question and its answers.) (有关此问题及其答案的循环数组的更多信息。)
You could make it non-enumerable: 您可以使其不可枚举:
Object.defineProperty(req.user.hails, "cancelEntry", {
value: function(index) {
this[index].cancel();
this.splice(index, 1);
}
});
In ES2015+, you could even create a subclass of Array
that had cancelEntry
on its prototype... 在ES2015 +中,您甚至可以创建在其原型上具有cancelEntry
的Array
子类...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.