避免对象Javascript中的重复
我有下一个目标:避免对象Javascript中的重复,javascript,arrays,duplicates,javascript-objects,Javascript,Arrays,Duplicates,Javascript Objects,我有下一个目标: var persons= {}; persons["Matt"].push("A"); persons["Matt"].push("B"); persons["Matt"].push("C"); 我想知道对象是否包含我试图插入的元素 例如: 有人知道一种方法吗 编辑更多详细信息: 我有一个关于下一个代码的示例: function insertIfNotThere(array, item) { if (array.indexOf(item) === -1) {
var persons= {};
persons["Matt"].push("A");
persons["Matt"].push("B");
persons["Matt"].push("C");
我想知道对象是否包含我试图插入的元素
例如:
有人知道一种方法吗
编辑更多详细信息:
我有一个关于下一个代码的示例:
function insertIfNotThere(array, item) {
if (array.indexOf(item) === -1) {
array.push(item);
}
}
function EventManager(target) {
var target = target || window, events = {};
this.observe = function(eventName, cb) {
if (events[eventName]){
insertIfNotThere(events[eventName], cb);
}else{
events[eventName] = []; events[eventName].push(cb);
}
return target;
};
this.fire = function(eventName) {
if (!events[eventName]) return false;
for (var i = 0; i < events[eventName].length; i++) {
events[eventName][i].apply(target, Array.prototype.slice.call(arguments, 1));
}
};
}
function insertIfNotThere(数组,项){
if(数组.indexOf(项)=-1){
数组。推送(项目);
}
}
功能事件管理器(目标){
var target=target | |窗口,events={};
this.observe=函数(eventName,cb){
if(事件[eventName]){
插入Fnotthere(事件[eventName],cb);
}否则{
事件[eventName]=[];事件[eventName]。推送(cb);
}
回报目标;
};
this.fire=函数(eventName){
如果(!events[eventName])返回false;
对于(var i=0;i
我使用您的方法检查具有指定内容的元素是否存在。但是它推动元素一直。。。我不知道发生了什么…用于检查A是否存在。如果A不存在(is-1),请将其添加到数组中:
if (persons['Matt'].indexOf('A') === -1) {
persons['Matt'].push('A');
}
第一件事。当你这样做的时候
persons= {};
您正在创建一个名为persons
的全局属性,并为其指定一个空对象。这里可能需要一个局部变量。所以,把它改成
var persons = {};
然后,当您在对象中创建一个新键时,默认情况下,该值将为undefined
。在您的情况下,需要存储一个数组。所以,你必须像这样初始化它
persons['Matt'] = [];
if (persons['Matt'].indexOf("A") === -1) {
persons['Matt'].push("A");
}
if (persons['Matt'].indexOf("B") === -1) {
persons['Matt'].push("B");
}
然后,您可以使用该函数确定要添加的项是否已存在于数组中(如果在数组中未找到该项,则返回-1
),如下所示
persons['Matt'] = [];
if (persons['Matt'].indexOf("A") === -1) {
persons['Matt'].push("A");
}
if (persons['Matt'].indexOf("B") === -1) {
persons['Matt'].push("B");
}
您可以创建一个函数来执行此操作
function insertIfNotThere(array, item) {
if (array.indexOf(item) === -1) {
array.push(item);
}
}
var persons = {};
persons['Matt'] = [];
insertIfNotThere(persons['Matt'], 'A');
insertIfNotThere(persons['Matt'], 'B');
// This will be ignored, as `A` is already there in the array
insertIfNotThere(persons['Matt'], 'A');
persons={}代码>创建一个对象,而不是一个数组。感谢您的更正:)我将编辑我的问题。非常感谢:我最喜欢的回答是,除了解决问题之外,还可以教授。这对我帮助很大抱歉,我正在尝试解决一个错误(与主要问题相关),但我无法。。。你的方法不能正确地与我的脚本一起工作。。。你知道为什么吗?我用更多的细节编辑了我的问题。。。“对不起!T_T@MartaFernandezelse事件[eventName]=[];事件[eventName]。推送(cb)
应该是否则{events[eventName]=[];events[eventName].push(cb);}
对不起,在我的代码中,我用了你告诉我的方式。。。这不是问题所在…:还有其他解释吗?(我绝望了…)嗨,谢谢你的密码。我选择了“thefourtheye”问题,因为它有一个有趣的解释。你能再看看我的问题吗?我编辑了更多的细节。。。(因为您的解决方案不适用于我的代码:S)