我的逻辑可能有什么问题?
如果我检查 (this.holdExists(x,y) != false)
,它会在任何情况下添加条目,或者如果我检查 (this.holdExists) 则根本不添加条目(x,y) == true)
.
//check if the hold with coordinates x,y already exists
holdExists: function(x,y) {
var precision = 0.01;
holds.forEach(function(obj) {
if ( (Math.abs(x - obj.x) < precision)
|| (Math.abs(y - obj.y) < precision) ) {
console.log('Already exists!');
return true
}
return false
});
},
// add hold by coordinates only
addCoordHold: function(x,y) {
if (this.holdExists(x,y) == true) {
var h = Hold(x,y);
holds.push(h);
console.log('added\n', x,y);
} else {
console.log('A hold already exists!');
}
},
最佳答案
您正在从传递给 forEach
的迭代器函数返回值,但 forEach
并不关心这些返回值,并且它们与返回无关holdExists
函数的值,正如您所定义的,它始终是未定义
。
您的意思可能是:
holdExists: function(x,y) {
var precision = 0.01;
var rv = false;
holds.some(function(obj) {
if ( (Math.abs(x - obj.x) < precision)
|| (Math.abs(y - obj.y) < precision) ) {
console.log('Already exists!');
rv = true;
return true;
}
});
return rv;
},
这做了几件事:
它声明一个变量
rv
,用作holdExists
函数的返回值。它从
forEach
切换到some
,以便您可以提前结束迭代(forEach
将始终循环所有元素)。如果找到匹配项,它会将
rv
设置为true
。如果找到匹配项,它会停止
some
循环。它为
holdExists
函数设置返回值。
关于javascript - 此条目存在检查中可能出现什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20461184/