Javascript IndexOf无法正确处理包含数组的对象
我有一个关于下一个代码的示例:Javascript IndexOf无法正确处理包含数组的对象,javascript,arrays,duplicates,listener,indexof,Javascript,Arrays,Duplicates,Listener,Indexof,我有一个关于下一个代码的示例: function insertIfNotThere(array, item) { /* Push the new element everytime: because return -1 */ if (array.indexOf(item) === -1) { array.push(item); } /*But this log shows 1, 2, 3 and so on...*/ console.log
function insertIfNotThere(array, item) {
/* Push the new element everytime: because return -1 */
if (array.indexOf(item) === -1) {
array.push(item);
}
/*But this log shows 1, 2, 3 and so on...*/
console.log(array.length);
}
function EventManager(target) {
var target = target || window, events = {};
this.observe = function(eventName, cb) {
if (events[eventName]){
/* This insert the new event everytime: indexOf doesn't work... */
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));
}
};
}
我使用insertIfNotThere方法来检查具有指定内容的元素是否存在。但是它推动元素一直。。。我不知道发生了什么
我用一个按钮创建了这个事件:如果我在这个按钮中多次单击,复制元素…我解决了这个问题,如下所示:
function indexOf(array, item) {
for (var i = 0; i < array.length; i++) {
if (array[i].toString() === item.toString()) return i;
}
return -1;
}
此方法适用于我的代码。cb是什么类型?它是一个对象吗?是一个函数cb=callback。我想管理自定义事件。我使用它如下:registerHandler'mycustomevent',函数{console.logDetect;};所以,它是一个对象,函数就是对象!对不起,我不知道它是一个物体。。。IndexOf不适用于对象?请将您的编辑作为答案发布,而不是将其放入问题中。我们鼓励自答问题,只要它们是好问题。