Javascript 检查对象中是否存在元素
我有一组单选按钮,当选择一个单选按钮时,元素被推入一个对象中 然后我需要获取对象中元素的值,然后将它们放入数组中,如果它们还没有在数组中的话 我的问题是,我一直在用这个函数获取每个值的数组中的重复项或更多项,因为我没有正确地检查它们是否存在 如何检查数组中是否已存在该元素,然后将其排除在添加之外Javascript 检查对象中是否存在元素,javascript,arrays,angularjs,object,Javascript,Arrays,Angularjs,Object,我有一组单选按钮,当选择一个单选按钮时,元素被推入一个对象中 然后我需要获取对象中元素的值,然后将它们放入数组中,如果它们还没有在数组中的话 我的问题是,我一直在用这个函数获取每个值的数组中的重复项或更多项,因为我没有正确地检查它们是否存在 如何检查数组中是否已存在该元素,然后将其排除在添加之外 _this.selected = {}; _this.selectedArray = []; //loop through the object ang
_this.selected = {};
_this.selectedArray = [];
//loop through the object
angular.forEach(_this.selected, function ( item ){
//if it is not the first time the array is getting data loop through the array
if(_this.selectedArray.length > 0) {
_this.selectedArray.forEach(function (node){
//check to see if the item already exists-- this is where it is failing
//and running the loop too many times
if(node.id !== item.id){
_this.selectedArray.push(item);
}
});
} else {
_this.selectedArray.push(share);
}
});
您试过jQuery的inArray
吗
它的工作原理与String
上的indexOf
方法相同
如果$.inArray(node,selectedArray)==-1//元素不在数组中,您可以尝试。
您可以在该数组上运行此函数以将其减少为唯一值,而不是应用复杂的代码来检查数组是否有元素
var getOnlyUniqueValuesInArray = function(arrayObj) {
return arrayObj.reduce(function(a, b) {
if (a.indexOf(b) < 0) a.push(b);
return p;
}, []);
};
var getOnlyUniqueValuesInArray=函数(arrayObj){
返回arrayObj.reduce(函数(a,b){
如果(a.indexOf(b)<0)a.push(b);
返回p;
}, []);
};
您可以使用附加哈希来检查是否已将项添加到数组中
_this.selected = {};
_this.selectedArray = [];
_this.selectedHash = {};
//loop through the object
angular.forEach(_this.selected, function ( item ){
if(_this.selectedHash[item.id]) { return; }
_this.selectedArray.push(item);
_this.selectedHash[item.id] = 1;
});
嗨,那会有帮助的
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope){
var app = angular.module('app', []);
app.controller('firstCtrl', function($scope) {
_this.selected = {};
_this.selectedArray = [];
//loop through the object
angular.forEach(_this.selected, function(item) {
//if it is not the first time the array is getting data loop through the array
if (_this.selectedArray.length > 0) {
var canAdd = true;
_this.selectedArray.forEach(function(node) {
//do not add iny any of node.id will be equal to item.id
if (node.id == item.id) {
canAdd = false;
}
});
if(canAdd){
_this.selectedArray.push(item);
};
} else {
_this.selectedArray.push(share);
}
});
})
});
“被推入一个物体”如何?“推入物体”是什么意思我的意思是对象是使用键、值对进行更新的。您是否使用id作为键?如果是,那么怎么会有重复项呢?node
是元素还是对象。“node”是对象,它们都是对象,我正在比较每个对象的id。他可能有jQuery,但可能不太可能,因为他使用的是angularjs。我本以为使用angularjs的人很可能也会使用jQuery。嗯,考虑到angularjs的关键在于javascript不直接与dom交互,jquery对于angularjs变得毫无用处(除了一些辅助方法,比如这个),根据他的评论,这个解决方案无论如何都不会工作,因为他使用的是对象。回到绘图板:)您没有使用canAdd
。没问题。顺便说一句,由于其他原因,这仍然不起作用。首先:您在对所选阵列进行迭代时正在更改它。@YuryTarabanko if(canAdd)。。应该在回路块之后,而不是内部。我已经更新了答案,现在可以了。最后一个建议是:由于您使用的是nativeforEach
,因此当您需要根据某个谓词检查数组元素时,似乎some
或every
更适合<代码>!selectedArray.some(函数(节点){return node.id==item.id;})
或selectedArray.every(函数(节点){return node.id!=item.id;})
:)