我有下一个代码:
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;
}
此方法适用于我的代码。
关于javascript - IndexOf 无法正确处理包含数组的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27355555/