JavaScript是一门Web编程语言,用来实现网页的交互功能,它和HTML、CSS共同组成了个Web开发的基础工具集合,也是前端开发者必备的技能;学习JavaScript教程可以了解它在网页开发中的所有特性和相关概念,让我们能够更加快速的去开发Web应用。
在我们的学校课程中,我们学习了代数中的变量与方程。假设a=30,b=12,c=a-b,则c=18,即像a、b、c这样的变量存储着数字。在JavaScript等编程语言中,变量包含值(信息片段)并存储于计算机内存中,且具备可修改特性。
标准:ECMA-262
Contents:
有效标识符名称
UnicodeLetter:大写字母(Lu), 小写字母(Ll), 标题格字母 (Lt), 修饰字母(Lm), 其他字母(Lo)或字母数字(Nl).
Unicode组合标记非间距标记(Mn) 间距组合标记(Mc)。
UnicodeDigit:十进制数字(Nd),连接符标点(Pc).
UnicodeEscapeSequence:Unicode转义序列在标识符名称中同样允许使用,在此类情况下它们将作为单个字符。
无效的变量名
有效变量名
声明JavaScript变量的一种较为合理的方式
始终以统一的方式声明变量,并置于其作用域顶部。建议每行仅声明一个变量。逗号前置、单行var语句、多行var语句等形式均可采用,但需确保整个项目中风格一致。
// Bad Practice
var foo = 1,
bar = 2;
var baz;
var pony;
var x
, y;
//------------------------------
var foo = 1;
if (foo > 1) {
var bar = 2;
}
// Good Practice
var foo = 1;
var bar = 2;
var baz;
var pony;
var x;
var y;
//------------------------------
var foo = 1;
var bar;
if (foo > 1) {
bar = 2;
}
执行一下始终使用 var 声明变量。否则将导致全局变量。
建议将未赋值的变量声明置于最后。这种做法在后续可能需要根据先前已赋值的变量进行赋值时,能有效提升代码的可维护性。
// bad
var i, len, dragonball,
items = getItems(),
goSportsTeam = true;
// bad
var i;
var items = getItems();
var dragonball;
var goSportsTeam = true;
var len;
// good
var items = getItems();
var goSportsTeam = true;
var dragonball;
var length;
var i;
执行一下应在作用域顶部声明变量。这有助于避免由变量声明及赋值操作提升所引发的问题。
// bad
function() {
test();
console.log('doing stuff..');
//..other stuff..
var name = getName();
if (name === 'test') {
return false;
}
return name;
}
// good
function() {
var name = getName();
test();
console.log('doing stuff..');
//..other stuff..
if (name === 'test') {
return false;
}
return name;
}
// bad - unnecessary function call
function() {
var name = getName();
if (!arguments.length) {
return false;
}
this.setFirstName(name);
return true;
}
// good
function() {
var name;
if (!arguments.length) {
return false;
}
name = getName();
this.setFirstName(name);
return true;
}
执行一下Hoisting
变量声明会被提升至其作用域的顶部,但其赋值操作不会提升。
// we know this wouldn't work (assuming there
// is no notDefined global variable)
function example() {
console.log(notDefined); // => throws a ReferenceError
}
// creating a variable declaration after you
// reference the variable will work due to
// variable hoisting. Note: the assignment
// value of `true` is not hoisted.
function example() {
console.log(declaredButNotAssigned); // => undefined
var declaredButNotAssigned = true;
}
// The interpreter is hoisting the variable
// declaration to the top of the scope,
// which means our example could be rewritten as:
function example() {
var declaredButNotAssigned;
console.log(declaredButNotAssigned); // => undefined
declaredButNotAssigned = true;
}
执行一下匿名函数表达式会提升其变量名,但不会提升函数赋值。
function example() {
console.log(anonymous); // => undefined
anonymous(); // => TypeError anonymous is not a function
var anonymous = function() {
console.log('anonymous function expression');
};
}
执行一下命名函数表达式会提升变量名,而不会提升函数名或函数体。
function example() {
console.log(named); // => undefined
named(); // => TypeError named is not a function
superPower(); // => ReferenceError superPower is not defined
var named = function superPower() {
console.log('Flying');
};
}
// the same is true when the function name
// is the same as the variable name.
function example() {
console.log(named); // => undefined
named(); // => TypeError named is not a function
var named = function named() {
console.log('named');
}
}
执行一下变量求值
未被赋值的变量或数组元素其值为 undefined。对未赋值变量进行求值的结果取决于其声明方式:
若未赋值的变量由var声明,在数值上下文中求值结果为undefined值或NaN。
若未使用var语句声明未赋值的变量,对其进行求值将导致运行时错误。
查看以下声明:
var x;
print("The value of x is : " + x); // prints "The value of x is : undefined"
print("The value of y is : " + y); // throws reference error exception
执行一下可使用undefined判断变量是否有值。
在以下语句中,变量x未被赋值,且if语句的条件评估结果为真。
变量用法:
变量的声明与使用可分为局部和全局两种方式。在函数内部声明JavaScript变量时,该变量称为局部变量,其作用域仅限于该函数内部。不同函数中可使用同名变量。在函数外部声明的变量则称为全局变量。
可选择使用var声明全局变量(例如var empCode)。但在函数内部必须通过var声明变量。
如何检查JavaScript中变量是否存在?使用typeof检测未定义,或try/catch捕获未声明错误。
要检查变量是否已定义,可使用typeof操作符。若结果为'undefined'则变量未定义。注意直接与undefined比较在变量未声明时可能报错,而typeof始终安全。typeof 运算符。以下警告框将返回"undefined",即变量"abc"未定义。
您可通过如下if语句检测变量是否已定义:if (typeof myVar !== 'undefined') { ... }
JavaScript:常量
在JavaScript中,常量通过const关键字声明,且必须在声明时赋值。常量可以是全局的,或在声明它的函数内局部有效。
常量是只读的,因此无法在后续修改其值。
在 JavaScript 中命名常量遵循与命名变量相同的规则,不同之处在于必须始终使用 const 关键字,即使是全局常量也不例外。
若省略关键字,则假定该标识符表示变量。
Example:const country = 'India';
//You cannot declare a constant with the same name as a function
// or variable in the same scope. Following statements create error.
function abc()
{
const abc = 55;
}
function abc()
{
const x = 15;
var x;
}
执行一下JavaScript:数据类型
值是指一段信息,可以是数值、字符串、布尔值、空值等类型。JavaScript可识别以下类型的值。
Types | Description | 示例 |
---|---|---|
String | 由引号包裹的一系列字符。字符串必须由相同类型的引号定界,可采用单引号(')或双引号(")。 | “google.com”、“yahoo.com” |
Numbers | 任意数值。数值可为正数或负数。 | 45, 45887, -45, 12.23, -145.55 |
逻辑(布尔型) | 逻辑真值或假值。用于评估条件是否为真或假。 | true, false |
null | 一个表示空值(即无值或空无)的特殊关键字。由于JavaScript区分大小写,null不同于Null、NULL或任何其他变体。 | |
undefined | 值为 undefined 的顶级属性,undefined 本身也是一种原始值类型。 |
JavaScript:数据类型转换
JavaScript 是一种动态类型语言。因此,在声明变量时无需指定其数据类型。在脚本执行过程中,数据类型会根据需要自动转换。
例如,我们按如下方式在'age'变量中定义一个人的年龄:
将字符串值存储至所述变量。
由于JavaScript采用动态类型,上述赋值操作不会引发错误。
JavaScript:表达式
以下表达式包含字符串值、数值及+运算符。JavaScript会将数值转换为字符串。
x = "What is your age ?" + 21 // returns "What is your age ?21 "
y = 21 + " is my age. " // returns "21 is my age."
执行一下以下表达式包含+及-operators.
以下表达式包含星号(*)及/operators.
JavaScript:Unicode 转义序列
转义序列 | 代码单元值 | Name | Symbol |
\b | \u0008 | backspace | <BS> |
\t | \u0009 | 水平制表符 | <HT> |
\n | \u000A | 换行(新行) | <LF> |
\v | \u000B | 垂直制表符 | <VT> |
\f | \u000C | 换页符 | <FF> |
\r | \u000D | 回车符 | <CR> |
\" | \u0022 | 双引号 | " |
\' | \u0027 | 单引号 | ' |
\\ | \u005C | backslash | \ |
JavaScript:保留字
以下表格中的词汇为保留字,不可用作JavaScript的变量、函数、方法或对象名称。其中部分单词属于JavaScript当前使用的关键字;其余词语为保留供未来使用的标识符。
保留字列表:
break | for | throw |
case | function | try |
catch | if | typeof |
continue | in | var |
default | instanceof | void |
delete | new | while |
do | return | with |
else | switch | |
finally | this |
以下单词被保留为未来关键字:
abstract | export | long | synchronized |
boolean | extends | native | throws |
byte | final | package | transient |
char | float | private | volatile |
class | goto | protected | |
const | implements | public | |
debugger | import | short | |
double | int | static | |
enum | interface | super |