JavaScript 循环变量作用域 [英] JavaScript loop variable scope

查看:34
本文介绍了JavaScript 循环变量作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于 JavaScript 变量范围的一个简单问题.

Just a quick question about the scoping of JavaScript variables.

为什么alert() 函数会打印i 的值而不是返回undefined?

Why does the alert() function print the value of i instead of returning undefined?

$(document).ready(function () {
    for(var i = 0; i < 10; i += 1){
    }

     alert("What is 'i'? " + i);
});

我对 JS 还很陌生,在我涉足过的几乎所有其他语言中,for 循环范围内的声明将包含该循环的值,但在这种情况下不是,为什么?

I'm fairly new to JS, and in nearly all other languages I've dabbled, a declaration in the scope of the for loop would contain the value to that said loop, but not in this case, why?

什么是我"?10' 被打印出来.

推荐答案

请参阅 MDN 中的初始化参数"for#Parameters" rel="noreferrer">for-loop:

See the MDN for the "initialization parameters" of a for-loop:

一个表达式(包括赋值表达式)或变量声明.通常用于初始化计数器变量.此表达式可以选择使用 var 关键字声明新变量.这些变量不是循环的局部变量,即它们在 for 循环所在的同一范围内. 该表达式的结果被丢弃.

An expression (including assignment expressions) or variable declaration. Typically used to initialize a counter variable. This expression may optionally declare new variables with the var keyword. These variables are not local to the loop, i.e. they are in the same scope the for loop is in. The result of this expression is discarded.

这篇关于JavaScript 循环变量作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆