这个for循环是如何工作和结束的

How does this for loop work and end?

本文关键字:工作 结束 循环 for 何工作 这个      更新时间:2023-09-26

有两个初始化,没有" x<y "来限制迭代。那么这个循环是如何工作的呢?

var features = [{
  position: new google.maps.LatLng(-33.91721, 151.22630),
  type: 'info'
}, {
  position: new google.maps.LatLng(-33.91539, 151.22820),
  type: 'info'
}, {
  position: new google.maps.LatLng(-33.91747, 151.22912),
  type: 'info'
}];
for (var i = 0, feature; feature = features[i]; i++) {
  addMarker(feature);
}

在Javascript中访问超出边界的索引将产生undefined,这是一个假值。一旦索引超出了范围,feature = features[i]赋值(计算结果为它所赋的值)将被认为是false,并且循环将退出。

有一个快捷方式,如果您希望分配和返回相同的值,可以执行return variable = value。这将返回value

var x;
function notify(v){
  return x = v;
}
console.log(notify(10))

所以在你的代码中,当你执行feature = features[3]时,因为features[3]是未定义的,它返回undefined,这是假的。因此你的循环中断了。

var x = 0;
if(x = 1){
  console.log('Success')
}
else{
  console.log('Error')
}
if(x = undefined){
  console.log('Success')
}
else{
  console.log('Error')
}

注意如果features[i]返回0falseundefined或任何其他假值,则循环将中断。