编辑:为了简单起见,请考虑以下代码:
var z = {x: 1, y: 1};
console.log(z.x+5 + ' ' + z.y+5);
为什么输出是(6,15)而不是(6,6)?
编辑前:我有以下功能:
function findPath(startX, startY, goalX, goalY){
var queue = [],
candidates = [],
path = [];
queue.push({x: startX, y: startY, searchDistance: 0, hasBeenSearched: true});
fillQueue();
function fillQueue(){
setInnerHTML(queue[0].x, queue[0].y, '.');
for(var i=-1; i<=1; i++){
if(queue[0].x + i < 0 || queue[0].x + i > boardHeight - 1){
continue;
}
for(var j=-1; j<=1; j++){
if(queue[0].y + j < 0 || queue[0].y + j > boardWidth - 1){
continue;
}
if(i == 0 && j == 0){
continue;
}
if(cells[queue[0].x + i][queue[0].y + j].type.blockMovement == true || findCell(queue[0].x + i, queue[0].y + j).hasBeenSearched == true){
console.log(queue[0].x + i + ' ' + queue[0].y + j)
continue;
}
if((queue[0].x + i == goalX) && (queue[0].y + j == goalY)){
setInnerHTML(queue[0].x + i, queue[0].y + j, '.');
candidates.push(queue[0]);
candidates.push({x: queue[0].x + i, y: queue[0].y + j, searchDistance: queue[0].searchDistance + 1, hasBeenSearched: true});
//fillPath();
return path;
}
queue.push({x: queue[0].x + i, y: queue[0].y + j, searchDistance: queue[0].searchDistance + 1, hasBeenSearched: true});
}
}
candidates.push(queue.shift());
if(queue.length > 0){
setTimeout(fillQueue, 0);
}else{
return 'no path found';
}
function findCell(x,y){
for(var i=0; i<queue.length; i++){
if(queue[i].x == x && queue[i].y == y){
return queue[i];
}else if(i == queue.length - 1 && (queue[i].x != x || queue[i].y != y)){
return {hasBeenSearched: false};
}
}
}
}
}
这是我最近重写的寻路算法的一部分,我遇到了以下问题。在内部 for 循环中,当检查此条件 findCell(queue[0].x + i,queue[0].y + j).hasBeenSearched == true
时,第二个参数 的值>queue[0].y
和 j
被连接起来,而不是仅仅被添加,而第一个参数的相同条件可以正常工作(其中的值被添加)。我花了几个小时试图弄清楚这一点,但我不知道发生了什么。值 queue[0].y
和 j
都是数字(我通过控制台记录 typeof
它们进行了检查),并且应该像这样添加第一个参数中的类似值。任何帮助指出我做错了什么的帮助将不胜感激。预先感谢您。
Codepen 链接:http://codepen.io/Furmanus/pen/LkXVwO/?editors=0011
最佳答案
JS 表达式是从左到右计算的。当它到达最后一个 +
时,它正在计算 ('6 1' + 5)
。
将最后一部分放在括号中以强制对其进行单独计算:console.log(z.x+5 + ' ' + (z.y+5))
。
您还可以使用括号记录多个内容,这将避免此问题:console.log(z.x+5, z.y+5)
。
关于javascript - if 条件内连接的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38817127/