Javascript for循环中的意外值

Javascript for循环中的意外值,javascript,arrays,loops,variables,behaviorsubject,Javascript,Arrays,Loops,Variables,Behaviorsubject,我完全搞不懂为什么变量端在整个循环过程中没有改变。虽然我成功地增加了变量j,但它不会更改包含引用变量j的代码段的变量end的值。有人能帮我吗 const number=[0,1,0,2,3,5,0,10,88]; 函数移动零点(arr){ const lastIndex=arr.length-1; 设j=0; 设end=arr[lastIndex-j]; 用于(arr的let项目){ console.log(end);//异常行为 console.log(j++);//按预期运行 } cons

我完全搞不懂为什么变量端在整个循环过程中没有改变。虽然我成功地增加了变量j,但它不会更改包含引用变量j的代码段的变量end的值。有人能帮我吗

const number=[0,1,0,2,3,5,0,10,88];
函数移动零点(arr){
const lastIndex=arr.length-1;
设j=0;
设end=arr[lastIndex-j];
用于(arr的let项目){
console.log(end);//异常行为
console.log(j++);//按预期运行
}
console.log(end)//异常行为
}

console.log(移动零(数字))它不会更改,因为您从未在循环中更新
end
的值:

const number=[0,1,0,2,3,5,0,10,88];
函数移动零点(arr){
const lastIndex=arr.length-1;
设j=0;
设end=arr[lastIndex-j];
用于(arr的let项目){
end=arr[lastIndex-j];//更改end的值
console.log(end);//异常行为
console.log(j++);//按预期运行
}
console.log(end)//异常行为
}

console.log(移动零(数字))它不会更改,因为您从未在循环中更新
end
的值:

const number=[0,1,0,2,3,5,0,10,88];
函数移动零点(arr){
const lastIndex=arr.length-1;
设j=0;
设end=arr[lastIndex-j];
用于(arr的let项目){
end=arr[lastIndex-j];//更改end的值
console.log(end);//异常行为
console.log(j++);//按预期运行
}
console.log(end)//异常行为
}
console.log(移动零(数字))
那代码已经发生了。你需要它现在发生,以获得当前值


那代码已经发生了。您现在需要它来获取当前值…

好吧,您永远不会在循环中更新
end
值,所以它不会改变,您只需记录它,永远不会使用
end
变量进行任何其他操作,所以它不是奇怪的,这是意料之中的。您可能希望将end assingment移动到loopwell内部,您永远不会更新循环中的
end
值,因此它不会更改,您只需记录它,永远不会使用
end
变量进行任何其他操作,所以这不是奇怪的,这是意料之中的。您可能想将末端分配移动到回路内部谢谢。现在我明白了。:)非常感谢。现在我明白了。:)
const numbers = [0, 1, 0, 2, 3, 5, 0, 10, 88];

function moveZeros(arr) {
  const lastIndex = arr.length - 1;
  let j = 0;
  let end = (j)=>{arr[lastIndex - j]};

  for (let item of arr) {
    console.log(end(j)); // odd behavior 
    console.log(j++); // behaves as expected 
  }
  console.log(end) // odd behavior
}
console.log(moveZeros(numbers));