基于如下所示的快速模型,我需要将 URL 路由对象添加到我的应用程序中的 Array 属性。
在下面的函数中addAppRoute(routeObbj)
我想添加一个检查以查看要添加的新路由是否已存在于属性 this.cache.webDevAppRoutes
中
如何确保不添加重复项?它需要基于重复的 module
和 action
一样
var app = {
cache: {
webDevAppRoutes: [],
},
addAppRoute: function(route) {
var routes = this.cache.webDevAppRoutes;
routes.push(route);
},
getAppRoutes: function() {
var routes = this.cache.webDevAppRoutes;
console.log(routes);
},
addBookmarkAppRoutes: function() {
this.addAppRoute({
module: 'bookmarks',
action: 'view',
params: [{
id: 123
}],
});
this.addAppRoute({
module: 'bookmarks',
action: 'edit',
params: [{
id: 123
}],
});
this.addAppRoute({
module: 'bookmarks',
action: 'add',
params: [],
});
},
}
最佳答案
只需遍历数组并检查它是否还没有包含该 module
和 action
的条目。你可以使用Array#some
,例如:
if (routes.some(function(r) { return r.module == route.module && r.action == route.action)) {
// It's a duplicate
}
Array#some
返回 true
只要对其回调的调用返回真值;否则,它返回 false
。
在 ES2015 中,这更简洁一些:
if (routes.some(r => r.module == route.module && r.action == route.action)) {
// It's a duplicate
}
关于javascript - 检测 JavaScript 中的重复对象属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40781314/