值,变量,以及语式量

  • 版本网址缩略名: JavaScript/Guide/Values,_variables,_and_literals
  • 版本标题: 值,变量,以及语式量
  • 版本 id: 362203
  • 创建于:
  • 创建者: iwo
  • 是否是当前版本?
  • 评论

修订内容

(译注:标题中的literals或译为字面量/值,术语量/值,语式量/值)

本章讨论在JavaScript语言中,用以识别和描述JavaScript表达式基本构件的一些值:变量,常量和语式量。(译者:第一句话就好难译通顺,道非常之不可道,接近JS的本质了?)

JavaScript语言可以识别下面这些不同类型的值:

 
类型 类型值范例 / 注释
数字* 42, 3.14159
逻辑(布尔)* true / false
字符串* "Howdy"
null(译注:意为空) 一个特殊的用于表示空值的关键字;同时null也是一个初始值。因为JavaScript语言是区分大小写的,所以null不同于NullNULL或者任何其他变体
undefined(译注:意为未定义) 一个未定义时的顶级属性;undefined同时也是初始值

(*译注:因此处不是关键字,故译之)

这一值的类型的相关小集合,或称数据类型表,就让你能够执行对你的应用程序非常有用的函数。在整数和实数型数字之间并没有明确的类型分界。JavaScript中也没有明确的日期数据类型。尽管如此,你仍可以用Date对象以及相关的方法处理日期数据。

对象函数是本语言的另两个基本要素。你可以这样认为:对象是上面标着名字的用来盛放值的容器,而函数是你的应用可以执行的程序(功能模块)。

数据类型的转换

JavaScript是一种支持动态数据类型的语言。这意味着你定义变量时不必指定数据类型,而数据类型会在脚本执行需要时自动转换。那么,你可以这样来定义变量:

var answer = 42;

然后,你还可以给同一个变量分配个字符串值,例如:

answer = "Thanks for all the fish...";

因为JavaScript是动态类型的,这样的分配并不会导致提示出错。

在包含加法运算符的数字和字符串表达式中,JavaScript会把数字值转换为字符串。例如,假设有如下的语句:

x = "The answer is " + 42 // "The answer is 42"
y = 42 + " is the answer" // "42 is the answer"

在包含其它运算符(译注:如下面的“-”)时,JavaScript语言不会把数字变为字符。例如(译注:第一例是数学运算,第二例仍是字符串运算):

"37" - 7 // 30
"37" + 7 // "377"

字符串转换为数字

代表一个数字的值在内存中是作为字符串保存的,这种情况下,有一些方法可以进行转换。

parseInt()parseFloat()

参考:parseInt()parseFloat()的相关页面。

parseInt仅能够返回全部的数目字,所以使用它会丢失小数部分。另外,最好的parseInt实践是在使用时总包含一个基数(译注:即进位制)参数。

加法运算符

将字符串转换为数字的一个替代方法,是使用加法运算符。

"1.1" + "1.1" = "1.11.1"
(+"1.1") + (+"1.1") = 2.2   // Note: the parentheses are added for clarity, not required.

变量

在应用中,你会以有意义的名称命名变量,并使用来表示值。变量的名称,或称为变量标识符,需要遵守一定的规则。

在JavaScript语言中,一个标识符必须以字母、下划线(_)或者美元($)符号开头;后续的字符可以包含数目字(0-9)。因为JavaScript语言是区分大小写的,这里所指的字母可以是(大写的)“A”到字母“Z”和(小写的)“a”到“z”。

从JavaScript 1.5版开始,你可以使用ISO 8859-1或Unicode编码的字符作标识符,例如å和ü。你也可以使用\uXXXX字样的转义序列 {{anch("Unicode escape sequences")}}作标识符。

一些合法的名称,例如:Number_hits,temp99和_name

声明变量

你可以用以下两种方式声明变量:

  • 使用关键词var。例如,var x = 42。这个语法可以同时用来声明局部和全局变量。
  • 直接赋值。例如,x = 42。这样就声明了一个全局变量并会导致JavaScript编译时产生一个严格警告。因而你应避免使用这种非常规格式。

对变量求值

声明时未赋初值的变量,值会被设定为undefined(译注:即未定义值,本身也是一个值)

试图取得一个未定义变量会导致一个控制台ReferenceError例外错误被抛出:

var a;
console.log("The value of a is " + a); // logs "The value of a is undefined"
console.log("The value of b is " + b); // throws ReferenceError exception

你可以使用undefined条件来决定是否赋值给变量。以下的代码中,变量input未被赋值,因而if条件语句的求值结果是true

var input;
if(input === undefined){
  doThis();
} else {
  doThat();
}

The following is related to "Variables" section as potential values in assignment.

The undefined value behaves as false when used in a boolean context. For example, the following code executes the function myFunction because the myArray element is not defined:

var myArray = new Array();
if (!myArray[0]) myFunction(); 

The undefined value converts to NaN when used in numeric context.

var a;
a + 2 = NaN

When you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:

var n = null;
console.log(n * 32); // logs 0

变量的域

When you declare a variable outside of any function, it is called a global variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a local variable, because it is available only within that function.

JavaScript does not have block statement scope; rather, it will be local to the code that the block resides within. For example the following code will log 5, because the scope of x is the function (or global context) within which x is declared, not the block, which in this case is an if statement.

if (true) {
  var x = 5;
}
console.log(x);

Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of undefined.

/**
 * Example 1
 */
console.log(x === undefined); // logs "true"
var x = 3;


/**
 * Example 2
 */
// will return a value of undefined
var myvar = "my value";

(function() {
  console.log(myvar); // undefined
  var myvar = "local value";
})();

例子2,如上所示,将被解释为与下面相同:

var myvar = "my value";

(function() {
  var myvar;
  console.log(myvar); // undefined
  myvar = "local value";
})();

Because of hoisting, all var statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.

全局变量

need links to pages discussing scope chains and the global object Global variables are in fact properties of the global object. In web pages the global object is window, so you can set and access global variables using the window.variable syntax.

Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called phoneNumber is declared in a FRAMESET document, you can refer to this variable from a child frame as parent.phoneNumber.

常量

You can create a read-only, named constant with the const keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.

const prefix = '212';

A constant cannot change value through assignment or be re-declared while the script is running.

The scope rules for constants are the same as those for variables, except that the const keyword is always required, even for global constants. If the keyword is omitted, the identifier is assumed to represent a variable.

You cannot declare a constant with the same name as a function or variable in the same scope. For example:

// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;

// THIS WILL CAUSE AN ERROR ALSO
function f() {
  const g = 5;
  var g;

  //statements
}

语式量(译注:通过由一定字辞组成的语词表达式定义的常量)

You use literals to represent values in JavaScript. These are fixed values, not variables, that you literally provide in your script. This section describes the following types of literals:

  • {{anch("Array literals")}}
  • {{anch("Boolean literals")}}
  • {{anch("Floating-point literals")}}
  • {{anch("Integers")}}
  • {{anch("Object literals")}}
  • {{anch("String literals")}}

矩阵语式量

An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.

The following example creates the coffees array with three elements and a length of three:

var coffees = ["French Roast", "Colombian", "Kona"];

Note An array literal is a type of object initializer. See Using Object Initializers.

If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.

Array literals are also Array objects. See Array Object for details on Array objects.

矩阵语式量中的多余逗号

You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with undefined for the unspecified elements. The following example creates the fish array:

var fish = ["Lion", , "Angel"];

This array has two elements with values and one empty element (fish[0] is "Lion", fish[1] is undefined, and fish[2] is "Angel").

If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no myList[3]. All other commas in the list indicate a new element. (Note: trailing commas can create errors in older browser versions and it is a best practice to remove them.)

var myList = ['home', , 'school', ];

In the following example, the length of the array is four, and myList[0] and myList[2] are missing.

var myList = [ , 'home', , 'school'];

In the following example, the length of the array is four, and myList[1] and myList[3] are missing. Only the last comma is ignored.

var myList = ['home', , 'school', , ];

Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as undefined will increase your code's clarity and maintainability.

布尔语式量(译注:即逻辑语式量)

The Boolean type has two literal values: true and false.

Do not confuse the primitive Boolean values true and false with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See Boolean Object for more information.

整数(译注:原文如此,没写成“整数语式量”)

Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8).

  • Decimal integer literal consists of a sequence of digits without a leading 0 (zero).
  • Leading 0 (zero) on an integer literal indicates it is in octal. Octal integers can include only the digits 0-7.
  • Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.

Octal integer literals are deprecated and have been removed from the ECMA-262, Edition 3 standard (in strict mode). JavaScript 1.5 still supports them for backward compatibility.

Some examples of integer literals are:

0, 117 and -345 (decimal, base 10)
015, 0001 and -077 (octal, base 8) 
0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)

浮点语式量

A floating-point literal can have the following parts:

  • A decimal integer which can be signed (preceded by "+" or "-"),
  • A decimal point ("."),
  • A fraction (another decimal number),
  • An exponent.

The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").

Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12.

More succinctly, the syntax is:

[digits][.digits][(E|e)[(+|-)]digits]

For example:

3.14
2345.789
.3333333333333333333

对象语式量

An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.

The following is an example of an object literal. The first element of the car object defines a property, myCar; the second element, the getCar property, invokes a function (CarTypes("Honda")); the third element, the special property, uses an existing variable (Sales).

var Sales = "Toyota";

function CarTypes(name) {
  return (name == "Honda") ?
    name :
    "Sorry, we don't sell " + name + "." ;
}

var car = { myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales };

console.log(car.myCar);   // Saturn
console.log(car.getCar);  // Honda
console.log(car.special); // Toyota 

Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.

var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };

console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda

Please note:

var foo = {a: "alpha", 2: "two"};
console.log(foo.a);    // alpha
console.log(foo[2]);   // two
//console.log(foo.2);  // Error: missing ) after argument list
//console.log(foo[a]); // Error: a is not defined
console.log(foo["a"]); // alpha
console.log(foo["2"]); // two

字符串语式量

A string literal is zero or more characters enclosed in double (") or single (') quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:

  • "foo"
  • 'bar'
  • "1234"
  • "one line \n another line"
  • "John's cat"

You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the String.length property with a string literal:

"John's cat".length

You should use string literals unless you specifically need to use a String object. See String Object for details on String objects.

在字符串中使用的特殊字符

In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.

"one line \n another line"

The following table lists the special characters that you can use in JavaScript strings.

Table 2.1 JavaScript special characters
Character Meaning
\b Backspace
\f Form feed
\n New line
\r Carriage return
\t Tab
\v Vertical tab
\' Apostrophe or single quote
\" Double quote
\\ Backslash character (\).
\XXX The character with the Latin-1 encoding specified by up to three octal digits XXX between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.
\xXX The character with the Latin-1 encoding specified by the two hexadecimal digits XX between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.
\uXXXX The Unicode character specified by the four hexadecimal digits XXXX. For example, \u00A9 is the Unicode sequence for the copyright symbol. See {{anch("Unicode escape sequences")}}.

转义字符

For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.

You can insert a quotation mark inside a string by preceding it with a backslash. This is known as escaping the quotation mark. For example:

var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
console.log(quote);

The result of this would be:

He read "The Cremation of Sam McGee" by R.W. Service.

To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path c:\temp to a string, use the following:

var home = "c:\\temp";

You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.

var str = "this string \
is broken \
across multiple\
lines."
console.log(str);   // this string is broken across multiplelines.

Although JavaScript does not have "heredoc" syntax, you can get close by adding a linebreak escape and an escaped linebreak at the end of each line:

var poem = 
"Roses are red,\n\
Violets are blue.\n\
I'm schizophrenic,\n\
And so am I."

Unicode编码

Unicode is a universal character-coding standard for the interchange and display of principal written languages. It covers the languages of the Americas, Europe, Middle East, Africa, India, Asia, and Pacifica, as well as historic scripts and technical symbols. Unicode allows for the exchange, processing, and display of multilingual texts, as well as the use of common technical and mathematical symbols. It hopes to resolve internationalization problems of multilingual computing, such as different national character standards. Not all modern or archaic scripts, however, are currently supported.

The Unicode character set can be used for all known encoding. Unicode is modeled after the ASCII (American Standard Code for Information Interchange) character set. It uses a numerical value and name for each character. The character encoding specifies the identity of the character and its numeric value (code position), as well as the representation of this value in bits. The 16-bit numeric value (code value) is defined by a hexadecimal number and a prefix U, for example, U+0041 represents A. The unique name for this value is LATIN CAPITAL LETTER A.

Unicode is not supported in versions of JavaScript prior to 1.3.

兼容于ASCII和ISO标准的Unicode编码

Unicode is fully compatible with the International Standard ISO/IEC 10646-1; 1993, which is a subset of ISO 10646.

Several encoding standards (including UTF-8, UTF-16 and ISO UCS-2) are used to physically represent Unicode as actual bits.

The UTF-8 encoding of Unicode is compatible with ASCII characters and is supported by many programs. The first 128 Unicode characters correspond to the ASCII characters and have the same byte value. The Unicode characters U+0020 through U+007E are equivalent to the ASCII characters 0x20 through 0x7E. Unlike ASCII, which supports the Latin alphabet and uses a 7-bit character set, UTF-8 uses between one and four octets for each character ("octet" meaning a byte, or 8 bits.) This allows for several million characters. An alternative encoding standard, UTF-16, uses two octets to represent Unicode characters. An escape sequence allows UTF-16 to represent the whole Unicode range by using four octets. The ISO UCS-2 (Universal Character Set) uses two octets.

JavaScript and Navigator support for UTF-8/Unicode means you can use non-Latin, international, and localized characters, plus special technical symbols in JavaScript programs. Unicode provides a standard way to encode multilingual text. Since the UTF-8 encoding of Unicode is compatible with ASCII, programs can use ASCII characters. You can use non-ASCII Unicode characters in the comments, string literals, identifiers, and regular expressions of JavaScript.

Unicode转义序列

You can use the Unicode escape sequence in string literals, regular expressions, and identifiers. The escape sequence consists of six ASCII characters: \u and a four-digit hexadecimal number. For example, \u00A9 represents the copyright symbol. Every Unicode escape sequence in JavaScript is interpreted as one character.

The following code returns the copyright symbol and the string "Netscape Communications".

var x = "\u00A9 Netscape Communications";

The following table lists frequently used special characters and their Unicode value.

Table 2.2 Unicode values for special characters
Category Unicode value Name Format name
White space values \u0009 Tab <TAB>
\u000B Vertical Tab <VT>
\u000C Form Feed <FF>
\u0020 Space <SP>
Line terminator values \u000A Line Feed <LF>
\u000D Carriage Return <CR>
Additional Unicode escape sequence values \u0008 Backspace <BS>
\u0009 Horizontal Tab <HT>
\u0022 Double Quote "
\u0027 Single Quote '
\u005C Backslash \

The JavaScript use of the Unicode escape sequence is different from Java. In JavaScript, the escape sequence is never interpreted as a special character first. For example, a line terminator escape sequence inside a string does not terminate the string before it is interpreted by the function. JavaScript ignores any escape sequence if it is used in comments. In Java, if an escape sequence is used in a single comment line, it is interpreted as an Unicode character. For a string literal, the Java compiler interprets the escape sequences first. For example, if a line terminator escape character (e.g., \u000A) is used in Java, it terminates the string literal. In Java, this leads to an error, because line terminators are not allowed in string literals. You must use \n for a line feed in a string literal. In JavaScript, the escape sequence works the same way as \n.

JavaScript文件中的Unicode字符

Earlier versions of Gecko assumed the Latin-1 character encoding for JavaScript files loaded from XUL. Starting with Gecko 1.8, the character encoding is inferred from the XUL file's encoding. Please see International characters in XUL JavaScript for more information.

用Unicode编码显示字符

You can use Unicode to display the characters in different languages or technical symbols. For characters to be displayed properly, a client such as Mozilla Firefox or Netscape needs to support Unicode. Moreover, an appropriate Unicode font must be available to the client, and the client platform must support Unicode. Often, Unicode fonts do not display all the Unicode characters. Some platforms, such as Windows 95, provide partial support for Unicode.

To receive non-ASCII character input, the client needs to send the input as Unicode. Using a standard enhanced keyboard, the client cannot easily input the additional characters supported by Unicode. Sometimes, the only way to input Unicode characters is by using Unicode escape sequences.

For more information on Unicode, see the Unicode Home Page and The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996.

外部参考资源

{{autoPreviousNext("JSGChapters")}}

修订版来源

<p>(译注:标题中的literals或译为字面量/值,术语量/值,语式量/值)</p>
<p>本章讨论在JavaScript语言中,用以识别和描述JavaScript表达式基本构件的一些值:变量,常量和语式量。(译者:第一句话就好难译通顺,道非常之不可道,接近JS的本质了?)</p>
<h2 id=".E5.80.BC">值</h2>
<p>JavaScript语言可以识别下面这些不同类型的值:</p>
<table>
  <caption>
    &nbsp;</caption>
  <thead>
    <tr>
      <th scope="col">类型</th>
      <th scope="col">类型值范例 / 注释</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/Number" style="color: rgb(34, 85, 170); text-decoration: underline; line-height: 21px; " title="zh-CN/docs/JavaScript/Reference/Global Objects/Number">数字*</a></td>
      <td>42, 3.14159</td>
    </tr>
    <tr>
      <td><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/Boolean" style="color: rgb(34, 85, 170); text-decoration: underline; line-height: 21px; " title="zh-CN/docs/JavaScript/Reference/Global Objects/Boolean">逻辑(布尔)*</a></td>
      <td>true / false</td>
    </tr>
    <tr>
      <td><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/String" style="color: rgb(34, 85, 170); text-decoration: underline; line-height: 21px; " title="zh-CN/docs/JavaScript/Reference/Global Objects/String">字符串*</a></td>
      <td>"Howdy"</td>
    </tr>
    <tr>
      <td><span style="font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal; ">null</span><span _mce_style="line-height: 21px;" style="line-height: 21px;">(译注:意为空)</span></td>
      <td><span _mce_style="line-height: 21px;" style="line-height: 21px;">一个特殊的用于表示空值的关键字;同时</span><span _mce_style="line-height: 21px;" style="line-height: 21px;"><code _mce_style="font-size: 14px;" style="font-size: 14px;">null</code>也是一个初始值。因为</span><span _mce_style="line-height: 21px;" style="line-height: 21px;"><span _mce_style="line-height: 21px;" style="line-height: 21px;">JavaScript</span>语言是区分大小写的,所以</span><span _mce_style="line-height: 21px;" style="line-height: 21px;"><code _mce_style="font-size: 14px;" style="font-size: 14px;">null</code>不同于</span><span _mce_style="line-height: 21px;" style="line-height: 21px;"><code _mce_style="font-size: 14px;" style="font-size: 14px;">Null</code><span _mce_style="line-height: 21px;" style="line-height: 21px;">,</span><code _mce_style="font-size: 14px;" style="font-size: 14px;">NULL</code>或者任何其他变体</span></td>
    </tr>
    <tr>
      <td><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/undefined" style="color: rgb(34, 85, 170); text-decoration: underline; font-family: 'Courier New', 'Andale Mono', monospace; line-height: normal; " title="zh-CN/docs/JavaScript/Reference/Global Objects/undefined">undefined</a><span _mce_style="line-height: 21px;" style="line-height: 21px;"><span _mce_style="line-height: 21px;" style="line-height: 21px;"><span _mce_style="line-height: 21px;" style="line-height: 21px;"><span _mce_style="line-height: 21px;" style="line-height: 21px;">(译注:意为未定义)</span></span></span></span></td>
      <td><span _mce_style="line-height: 21px;" style="line-height: 21px;"><span _mce_style="line-height: 21px;" style="line-height: 21px;"><span _mce_style="line-height: 21px;" style="line-height: 21px;"><span _mce_style="line-height: 21px;" style="line-height: 21px;">当</span>一个</span></span>值</span><span _mce_style="line-height: 21px;" style="line-height: 21px;">未定义时的</span><span _mce_style="line-height: 21px;" style="line-height: 21px;"><span _mce_style="line-height: 21px;" style="line-height: 21px;">顶级属性;</span></span><span _mce_style="line-height: 21px;" style="line-height: 21px;"><span _mce_style="line-height: 21px;" style="line-height: 21px;"><code _mce_style="font-size: 14px;" style="font-size: 14px;">undefined</code>同时也是初始值</span></span>。</td>
    </tr>
  </tbody>
</table>
<p><span _mce_style="line-height: 21px;" style="line-height: 21px;">(*译注:因此处不是关键字,故译之)</span></p>
<p>这一值的类型的相关小集合,或称<em>数据类型表</em>,就让你能够执行对你的应用程序非常有用的函数。在整数和实数型数字之间并没有明确的类型分界。JavaScript中也没有明确的日期数据类型。尽管如此,你仍可以用<code><a _mce_href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Date" href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Date" title="zh-CN/docs/JavaScript/Reference/Global Objects/Date">Date</a></code>对象以及相关的方法处理日期数据。</p>
<p><a _mce_href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Object" href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Object" title="zh-CN/docs/JavaScript/Reference/Global Objects/Object">对象</a>和<a _mce_href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Function" href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Global_Objects/Function" title="zh-CN/docs/JavaScript/Reference/Global Objects/Function">函数</a>是本语言的另两个基本要素。你可以这样认为:对象是上面标着名字的用来盛放值的容器,而函数是你的应用可以执行的程序(功能模块)。</p>
<h3 id=".E6.95.B0.E6.8D.AE.E7.B1.BB.E5.9E.8B.E7.9A.84.E8.BD.AC.E6.8D.A2">数据类型的转换</h3>
<p>JavaScript是一种支持动态数据类型的语言。这意味着你定义变量时不必指定数据类型,而数据类型会在脚本执行需要时自动转换。那么,你可以这样来定义变量:</p>
<div style="overflow:hidden;">
  <pre class="brush: js">
var answer = 42;
</pre>
</div>
<p>然后,你还可以给同一个变量分配个字符串值,例如:</p>
<pre class="brush: js">
answer = "Thanks for all the fish...";</pre>
<p>因为JavaScript是动态类型的,这样的分配并不会导致提示出错。</p>
<p>在包含加法运算符的数字和字符串表达式中,JavaScript会把数字值转换为字符串。例如,假设有如下的语句:</p>
<pre class="brush: js">
x = "The answer is " + 42 // "The answer is 42"
y = 42 + " is the answer" // "42 is the answer"
</pre>
<p>在包含其它运算符(译注:如下面的“-”)时,JavaScript语言不会把数字变为字符。例如(译注:第一例是数学运算,第二例仍是字符串运算):</p>
<pre class="brush: js">
"37" - 7 // 30
"37" + 7 // "377"
</pre>
<h3 id=".E5.AD.97.E7.AC.A6.E4.B8.B2.E8.BD.AC.E6.8D.A2.E4.B8.BA.E6.95.B0.E5.AD.97">字符串转换为数字</h3>
<p>代表一个数字的值在内存中是作为字符串保存的,这种情况下,有一些方法可以进行转换。</p>
<h4 id="parseInt().E5.92.8CparseFloat()"><code>parseInt()</code>和<code>parseFloat()</code></h4>
<p>参考:<code><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/parseInt" title="zh-CN/docs/JavaScript/Reference/Global Objects/parseInt">parseInt()</a></code>和<code><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/parseFloat" title="zh-CN/docs/JavaScript/Reference/Global Objects/parseFloat">parseFloat()</a></code>的相关页面。</p>
<p><code>parseInt</code>仅能够返回全部的数目字,所以使用它会丢失小数部分。另外,最好的<code>parseInt</code>实践是在使用时总包含一个基数(译注:即进位制)参数。</p>
<h4 id=".E5.8A.A0.E6.B3.95.E8.BF.90.E7.AE.97.E7.AC.A6">加法运算符</h4>
<p>将字符串转换为数字的一个替代方法,是使用加法运算符。</p>
<pre class="brush: js">
"1.1" + "1.1" = "1.11.1"
(+"1.1") + (+"1.1") = 2.2   // Note: the parentheses are added for clarity, not required.</pre>
<h2 id=".E5.8F.98.E9.87.8F">变量</h2>
<p>在应用中,你会以有意义的名称命名变量,并使用来表示值。变量的名称,或称为<em>变量标识符</em>,需要遵守一定的规则。</p>
<p>在JavaScript语言中,一个标识符必须以字母、下划线(_)或者美元($)符号开头;后续的字符可以包含数目字(0-9)。因为JavaScript语言是区分大小写的,这里所指的字母可以是(大写的)“A”到字母“Z”和(小写的)“a”到“z”。</p>
<p>从JavaScript 1.5版开始,你可以使用ISO 8859-1或Unicode编码的字符作标识符,例如å和ü。你也可以使用\uXXXX字样的转义序列 {{anch("Unicode escape sequences")}}作标识符。</p>
<p>一些合法的名称,例如:<code>Number_hits,</code><code>temp99和</code><code>_name</code>。</p>
<h3 id=".E5.A3.B0.E6.98.8E.E5.8F.98.E9.87.8F">声明变量</h3>
<p>你可以用以下两种方式声明变量:</p>
<ul>
  <li>使用关键词<a _mce_href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Statements/var" href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Statements/var" title="zh-CN/docs/JavaScript/Reference/Statements/var">var</a>。例如,<code>var x = 42。这个语法可以同时用来声明</code><code><a _mce_href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Values,_variables,_and_literals$edit#Variable_Scope" href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Values,_variables,_and_literals$edit#Variable_Scope">局部和全局</a>变量。</code></li>
  <li>直接赋值。例如,<code>x = 42。这样就声明了一个</code><code><a _mce_href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Values,_variables,_and_literals$edit#Global_Variables" href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Values,_variables,_and_literals$edit#Global_Variables">全局变量</a>并会导致</code><code>JavaScript编译时产生一个严格警告。因而你应避免使用这种非常规格式。</code></li>
</ul>
<h3 id=".E8.AF.84.E4.BC.B0.E5.8F.98.E9.87.8F">对变量求值</h3>
<p>声明时未赋初值的变量,值会被设定为<code><a _mce_href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined" href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/undefined" title="en-US/docs/JavaScript/Reference/Global Objects/undefined">undefined</a>(译注:即未定义值,本身也是一个值)</code>。</p>
<p>试图取得一个未定义变量会导致一个控制台<code>ReferenceError</code>例外错误被抛出:</p>
<pre class="brush: js">
var a;
console.log("The value of a is " + a); // logs "The value of a is undefined"
console.log("The value of b is " + b); // throws ReferenceError exception
</pre>
<p>你可以使用<code>undefined条件来</code>决定是否赋值给变量。以下的代码中,变量<code>input</code>未被赋值,因而<code><a _mce_href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Statements/if...else" href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Statements/if...else" title="zh-CN/docs/JavaScript/Reference/Statements/if...else">if</a></code>条件语句的求值结果是<code>true</code>。</p>
<pre class="brush: js">
var input;
if(input === undefined){
  doThis();
} else {
  doThat();
}
</pre>
<p><span class="comment">The following is related to "Variables" section as potential values in assignment.</span></p>
<p>The <code>undefined</code> value behaves as <code>false</code> when used in a boolean context. For example, the following code executes the function <code>myFunction</code> because the <code>myArray</code> element is not defined:</p>
<pre class="brush: js">
var myArray = new Array();
if (!myArray[0]) myFunction(); 
</pre>
<p>The <code>undefined</code> value converts to <code>NaN</code> when used in numeric context.</p>
<pre class="brush: js">
var a;
a + 2 = NaN</pre>
<p>When you evaluate a null variable, the null value behaves as 0 in numeric contexts and as false in boolean contexts. For example:</p>
<pre class="brush: js">
var n = null;
console.log(n * 32); // logs 0
</pre>
<h3 id=".E5.8F.98.E9.87.8F.E7.9A.84.E5.9F.9F">变量的域</h3>
<p>When you declare a variable outside of any function, it is called a <em>global</em> variable, because it is available to any other code in the current document. When you declare a variable within a function, it is called a <em>local</em> variable, because it is available only within that function.</p>
<p>JavaScript does not have <a href="/zh-CN/docs/JavaScript/Guide/Statements#Block_Statement" title="zh-CN/docs/JavaScript/Guide/Statements#Block Statement">block statement</a> scope; rather, it will be local to the code that the block resides within. For example the following code will log <code>5</code>, because the scope of <code>x</code> is the function (or global context) within which <code>x</code> is declared, not the block, which in this case is an <code>if</code> statement.</p>
<pre class="brush: js">
if (true) {
  var x = 5;
}
console.log(x);
</pre>
<p>Another unusual thing about variables in JavaScript is that you can refer to a variable declared later, without getting an exception. This concept is known as hoisting; variables in JavaScript are in a sense "hoisted" or lifted to the top of the function or statement. However, variables that aren't initialized yet will return a value of <code>undefined</code>.</p>
<pre class="brush: js">
/**
 * Example 1
 */
console.log(x === undefined); // logs "true"
var x = 3;


/**
 * Example 2
 */
// will return a value of undefined
var myvar = "my value";

(function() {
  console.log(myvar); // undefined
  var myvar = "local value";
})();
</pre>
<p>例子2,如上所示,将被解释为与下面相同:</p>
<pre class="brush: js">
var myvar = "my value";

(function() {
  var myvar;
  console.log(myvar); // undefined
  myvar = "local value";
})();</pre>
<p>Because of hoisting, all <code>var</code> statements in a function should be placed as near to the top of the function as possible. This best practice increases the clarity of the code.</p>
<h3 id=".E5.85.A8.E5.B1.80.E5.8F.98.E9.87.8F">全局变量</h3>
<p><span class="comment">need links to pages discussing scope chains and the global object</span> Global variables are in fact properties of the <em>global object</em>. In web pages the global object is <code><a href="/zh-CN/docs/DOM/window" title="zh-CN/docs/DOM/window">window</a></code>, so you can set and access global variables using the <code>window.<em>variable</em></code> syntax.</p>
<p>Consequently, you can access global variables declared in one window or frame from another window or frame by specifying the window or frame name. For example, if a variable called <code>phoneNumber</code> is declared in a <code>FRAMESET</code> document, you can refer to this variable from a child frame as <code>parent.phoneNumber</code>.</p>
<h2 id=".E5.B8.B8.E9.87.8F">常量</h2>
<p>You can create a read-only, named constant with the <code><a href="/zh-CN/docs/JavaScript/Reference/Statements/const" title="zh-CN/docs/JavaScript/Reference/Statements/const">const</a></code> keyword. The syntax of a constant identifier is the same as for a variable identifier: it must start with a letter, underscore or dollar sign and can contain alphabetic, numeric, or underscore characters.</p>
<pre class="brush: js">
const prefix = '212';
</pre>
<p>A constant cannot change value through assignment or be re-declared while the script is running.</p>
<p>The scope rules for constants are the same as those for variables, except that the <code>const</code> keyword is always required, even for global constants. If the keyword is omitted, the identifier is assumed to represent a variable.</p>
<p>You cannot declare a constant with the same name as a function or variable in the same scope. For example:</p>
<pre class="brush: js">
// THIS WILL CAUSE AN ERROR
function f() {};
const f = 5;

// THIS WILL CAUSE AN ERROR ALSO
function f() {
  const g = 5;
  var g;

  //statements
}
</pre>
<h2 id=".E8.AF.AD.E5.BC.8F.E9.87.8F.EF.BC.88.E8.AF.91.E6.B3.A8.EF.BC.9A.E9.80.9A.E8.BF.87.E7.94.B1.E4.B8.80.E5.AE.9A.E5.AD.97.E8.BE.9E.E7.BB.84.E6.88.90.E7.9A.84.E8.AF.AD.E8.AF.8D.E8.A1.A8.E8.BE.BE.E5.BC.8F.E5.AE.9A.E4.B9.89.E7.9A.84.E5.B8.B8.E9.87.8F.EF.BC.89">语式量(译注:通过由一定字辞组成的语词表达式定义的常量)</h2>
<p>You use literals to represent values in JavaScript. These are fixed values, not variables, that you <em>literally</em> provide in your script. This section describes the following types of literals:</p>
<ul>
  <li>{{anch("Array literals")}}</li>
  <li>{{anch("Boolean literals")}}</li>
  <li>{{anch("Floating-point literals")}}</li>
  <li>{{anch("Integers")}}</li>
  <li>{{anch("Object literals")}}</li>
  <li>{{anch("String literals")}}</li>
</ul>
<h3 id=".E7.9F.A9.E9.98.B5.E8.AF.AD.E5.BC.8F.E9.87.8F">矩阵语式量</h3>
<p>An array literal is a list of zero or more expressions, each of which represents an array element, enclosed in square brackets ([]). When you create an array using an array literal, it is initialized with the specified values as its elements, and its length is set to the number of arguments specified.</p>
<p>The following example creates the <code>coffees</code> array with three elements and a length of three:</p>
<pre class="brush: js">
var coffees = ["French Roast", "Colombian", "Kona"];
</pre>
<p><strong>Note</strong> An array literal is a type of object initializer. See <a href="/zh-CN/docs/JavaScript/Guide/Working_with_Objects#Using_Object_Initializers" title="zh-CN/docs/JavaScript/Guide/Working with Objects#Using Object Initializers">Using Object Initializers</a>.</p>
<p>If an array is created using a literal in a top-level script, JavaScript interprets the array each time it evaluates the expression containing the array literal. In addition, a literal used in a function is created each time the function is called.</p>
<p>Array literals are also <code>Array</code> objects. See <a href="/zh-CN/docs/JavaScript/Guide/Predefined_Core_Objects#Array_Object" title="zh-CN/docs/JavaScript/Guide/Predefined Core Objects#Array Object">Array Object</a> for details on <code>Array</code> objects.</p>
<h4 id=".E7.9F.A9.E9.98.B5.E8.AF.AD.E5.BC.8F.E9.87.8F.E4.B8.AD.E7.9A.84.E5.A4.9A.E4.BD.99.E9.80.97.E5.8F.B7">矩阵语式量中的多余逗号</h4>
<p>You do not have to specify all elements in an array literal. If you put two commas in a row, the array is created with <code>undefined</code> for the unspecified elements. The following example creates the <code>fish</code> array:</p>
<pre class="brush: js">
var fish = ["Lion", , "Angel"];
</pre>
<p>This array has two elements with values and one empty element (<code>fish[0]</code> is "Lion", <code>fish[1]</code> is <code>undefined</code>, and <code>fish[2]</code> is "Angel").</p>
<p>If you include a trailing comma at the end of the list of elements, the comma is ignored. In the following example, the length of the array is three. There is no <code>myList[3]</code>. All other commas in the list indicate a new element. (<strong>Note:</strong> trailing commas can create errors in older browser versions and it is a best practice to remove them.)</p>
<pre class="brush: js">
var myList = ['home', , 'school', ];
</pre>
<p>In the following example, the length of the array is four, and <code>myList[0]</code> and <code>myList[2]</code> are missing.</p>
<pre class="brush: js">
var myList = [ , 'home', , 'school'];
</pre>
<p>In the following example, the length of the array is four, and <code>myList[1]</code> and <code>myList[3]</code> are missing. Only the last comma is ignored.</p>
<pre class="brush: js">
var myList = ['home', , 'school', , ];
</pre>
<p>Understanding the behavior of extra commas is important to understanding JavaScript as a language, however when writing your own code: explicitly declaring the missing elements as <code>undefined</code> will increase your code's clarity and maintainability.</p>
<h3 id=".E5.B8.83.E5.B0.94.E8.AF.AD.E5.BC.8F.E9.87.8F.EF.BC.88.E8.AF.91.E6.B3.A8.EF.BC.9A.E5.8D.B3.E9.80.BB.E8.BE.91.E8.AF.AD.E5.BC.8F.E9.87.8F.EF.BC.89">布尔语式量(译注:即逻辑语式量)</h3>
<p>The Boolean type has two literal values: <code>true</code> and <code>false</code>.</p>
<p>Do not confuse the primitive Boolean values <code>true</code> and <code>false</code> with the true and false values of the Boolean object. The Boolean object is a wrapper around the primitive Boolean data type. See <a href="/zh-CN/docs/JavaScript/Guide/Predefined_Core_Objects#Boolean_Object" title="zh-CN/docs/JavaScript/Guide/Predefined Core Objects#Boolean Object">Boolean Object</a> for more information.</p>
<h3 id=".E6.95.B4.E6.95.B0.EF.BC.88.E8.AF.91.E6.B3.A8.EF.BC.9A.E5.8E.9F.E6.96.87.E5.A6.82.E6.AD.A4.EF.BC.8C.E6.B2.A1.E5.86.99.E6.88.90.E2.80.9C.E6.95.B4.E6.95.B0.E8.AF.AD.E5.BC.8F.E9.87.8F.E2.80.9D.EF.BC.89">整数(译注:原文如此,没写成“整数语式量”)</h3>
<p>Integers can be expressed in decimal (base 10), hexadecimal (base 16), and octal (base 8).</p>
<ul>
  <li>Decimal integer literal consists of a sequence of digits without a leading 0 (zero).</li>
  <li>Leading 0 (zero) on an integer literal indicates it is in octal. Octal integers can include only the digits 0-7.</li>
  <li>Leading 0x (or 0X) indicates hexadecimal. Hexadecimal integers can include digits (0-9) and the letters a-f and A-F.</li>
</ul>
<p>Octal integer literals are deprecated and have been removed from the ECMA-262, Edition 3 standard (in <em>strict mode</em>). JavaScript 1.5 still supports them for backward compatibility.</p>
<p>Some examples of integer literals are:</p>
<pre class="eval">
0, 117 and -345 (decimal, base 10)
015, 0001 and -077 (octal, base 8) 
0x1123, 0x00111 and -0xF1A7 (hexadecimal, "hex" or base 16)
</pre>
<h3 id=".E6.B5.AE.E7.82.B9.E8.AF.AD.E5.BC.8F.E9.87.8F">浮点语式量</h3>
<p>A floating-point literal can have the following parts:</p>
<ul>
  <li>A decimal integer which can be signed (preceded by "+" or "-"),</li>
  <li>A decimal point ("."),</li>
  <li>A fraction (another decimal number),</li>
  <li>An exponent.</li>
</ul>
<p>The exponent part is an "e" or "E" followed by an integer, which can be signed (preceded by "+" or "-"). A floating-point literal must have at least one digit and either a decimal point or "e" (or "E").</p>
<p>Some examples of floating-point literals are 3.1415, -3.1E12, .1e12, and 2E-12.</p>
<p>More succinctly, the syntax is:</p>
<pre class="eval">
[digits][.digits][(E|e)[(+|-)]digits]
</pre>
<p>For example:</p>
<pre class="eval">
3.14
2345.789
.3333333333333333333
</pre>
<h3 id=".E5.AF.B9.E8.B1.A1.E8.AF.AD.E5.BC.8F.E9.87.8F">对象语式量</h3>
<p>An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.</p>
<p>The following is an example of an object literal. The first element of the <code>car</code> object defines a property, <code>myCar</code>; the second element, the <code>getCar</code> property, invokes a function <code>(CarTypes("Honda"));</code> the third element, the <code>special</code> property, uses an existing variable (<code>Sales</code>).</p>
<pre class="brush: js">
var Sales = "Toyota";

function CarTypes(name) {
  return (name == "Honda") ?
    name :
    "Sorry, we don't sell " + name + "." ;
}

var car = { myCar: "Saturn", getCar: CarTypes("Honda"), special: Sales };

console.log(car.myCar);   // Saturn
console.log(car.getCar);  // Honda
console.log(car.special); // Toyota 
</pre>
<p>Additionally, you can use a numeric or string literal for the name of a property or nest an object inside another. The following example uses these options.</p>
<pre class="brush: js">
var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" };

console.log(car.manyCars.b); // Jeep
console.log(car[7]); // Mazda
</pre>
<p>Please note:</p>
<pre class="brush: js">
var foo = {a: "alpha", 2: "two"};
console.log(foo.a);    // alpha
console.log(foo[2]);   // two
//console.log(foo.2);  // Error: missing ) after argument list
//console.log(foo[a]); // Error: a is not defined
console.log(foo["a"]); // alpha
console.log(foo["2"]); // two
</pre>
<h3 id=".E5.AD.97.E7.AC.A6.E4.B8.B2.E8.AF.AD.E5.BC.8F.E9.87.8F">字符串语式量</h3>
<p>A string literal is zero or more characters enclosed in double (<code>"</code>) or single (<code>'</code>) quotation marks. A string must be delimited by quotation marks of the same type; that is, either both single quotation marks or both double quotation marks. The following are examples of string literals:</p>
<ul>
  <li><code>"foo"</code></li>
  <li><code>'bar'</code></li>
  <li><code>"1234"</code></li>
  <li><code>"one line \n another line"</code></li>
  <li><code>"John's cat"</code></li>
</ul>
<p>You can call any of the methods of the String object on a string literal value—JavaScript automatically converts the string literal to a temporary String object, calls the method, then discards the temporary String object. You can also use the <code>String.length</code> property with a string literal:</p>
<pre class="brush: js">
"John's cat".length
</pre>
<p>You should use string literals unless you specifically need to use a String object. See <a href="/zh-CN/docs/JavaScript/Guide/Predefined_Core_Objects#String_Object" title="zh-CN/docs/JavaScript/Guide/Predefined Core Objects#String Object">String Object</a> for details on <code>String</code> objects.</p>
<h4 id=".E5.9C.A8.E5.AD.97.E7.AC.A6.E4.B8.B2.E4.B8.AD.E4.BD.BF.E7.94.A8.E7.9A.84.E7.89.B9.E6.AE.8A.E5.AD.97.E7.AC.A6">在字符串中使用的特殊字符</h4>
<p>In addition to ordinary characters, you can also include special characters in strings, as shown in the following example.</p>
<pre class="brush: js">
"one line \n another line"
</pre>
<p>The following table lists the special characters that you can use in JavaScript strings.</p>
<table class="standard-table">
  <caption style="text-align: left;">
    Table 2.1 JavaScript special characters</caption>
  <thead>
    <tr>
      <th scope="col">Character</th>
      <th scope="col">Meaning</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><code>\b</code></td>
      <td>Backspace</td>
    </tr>
    <tr>
      <td><code>\f</code></td>
      <td>Form feed</td>
    </tr>
    <tr>
      <td><code>\n</code></td>
      <td>New line</td>
    </tr>
    <tr>
      <td><code>\r</code></td>
      <td>Carriage return</td>
    </tr>
    <tr>
      <td><code>\t</code></td>
      <td>Tab</td>
    </tr>
    <tr>
      <td><code>\v</code></td>
      <td>Vertical tab</td>
    </tr>
    <tr>
      <td><code>\'</code></td>
      <td>Apostrophe or single quote</td>
    </tr>
    <tr>
      <td><code>\"</code></td>
      <td>Double quote</td>
    </tr>
    <tr>
      <td><code>\\</code></td>
      <td>Backslash character (\).</td>
    </tr>
    <tr>
      <td><code>\<em>XXX</em></code></td>
      <td>The character with the Latin-1 encoding specified by up to three octal digits <em>XXX</em> between 0 and 377. For example, \251 is the octal sequence for the copyright symbol.</td>
    </tr>
    <tr>
      <td><code>\x<em>XX</em></code></td>
      <td>The character with the Latin-1 encoding specified by the two hexadecimal digits <em>XX</em> between 00 and FF. For example, \xA9 is the hexadecimal sequence for the copyright symbol.</td>
    </tr>
    <tr>
      <td><code>\u<em>XXXX</em></code></td>
      <td>The Unicode character specified by the four hexadecimal digits <em>XXXX</em>. For example, \u00A9 is the Unicode sequence for the copyright symbol. See {{anch("Unicode escape sequences")}}.</td>
    </tr>
  </tbody>
</table>
<h4 id=".E8.BD.AC.E4.B9.89.E5.AD.97.E7.AC.A6">转义字符</h4>
<p>For characters not listed in Table 2.1, a preceding backslash is ignored, but this usage is deprecated and should be avoided.</p>
<p>You can insert a quotation mark inside a string by preceding it with a backslash. This is known as <em>escaping</em> the quotation mark. For example:</p>
<pre class="brush: js">
var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service.";
console.log(quote);
</pre>
<p>The result of this would be:</p>
<pre class="eval">
He read "The Cremation of Sam McGee" by R.W. Service.
</pre>
<p>To include a literal backslash inside a string, you must escape the backslash character. For example, to assign the file path <code>c:\temp</code> to a string, use the following:</p>
<pre class="brush: js">
var home = "c:\\temp";
</pre>
<p>You can also escape line breaks by preceding them with backslash. The backslash and line break are both removed from the value of the string.</p>
<pre class="brush: js">
var str = "this string \
is broken \
across multiple\
lines."
<span class="objectBox objectBox-text ">console.log(str);</span>   // <span class="objectBox objectBox-text ">this string is broken across multiplelines.</span>
</pre>
<p>Although JavaScript does not have "heredoc" syntax, you can get close by adding a linebreak escape and an escaped linebreak at the end of each line:</p>
<pre class="brush: js">
var poem = 
"Roses are red,\n\
Violets are blue.\n\
I'm schizophrenic,\n\
And so am I."
</pre>
<h2 id="Unicode.E7.BC.96.E7.A0.81">Unicode编码</h2>
<p>Unicode is a universal character-coding standard for the interchange and display of principal written languages. It covers the languages of the Americas, Europe, Middle East, Africa, India, Asia, and Pacifica, as well as historic scripts and technical symbols. Unicode allows for the exchange, processing, and display of multilingual texts, as well as the use of common technical and mathematical symbols. It hopes to resolve internationalization problems of multilingual computing, such as different national character standards. Not all modern or archaic scripts, however, are currently supported.</p>
<p>The Unicode character set can be used for all known encoding. Unicode is modeled after the ASCII (American Standard Code for Information Interchange) character set. It uses a numerical value and name for each character. The character encoding specifies the identity of the character and its numeric value (code position), as well as the representation of this value in bits. The 16-bit numeric value (code value) is defined by a hexadecimal number and a prefix U, for example, U+0041 represents A. The unique name for this value is LATIN CAPITAL LETTER A.</p>
<p><strong>Unicode is not supported in versions of JavaScript prior to 1.3.</strong></p>
<h3 id=".E5.85.BC.E5.AE.B9.E4.BA.8EASCII.E5.92.8CISO.E6.A0.87.E5.87.86.E7.9A.84Unicode.E7.BC.96.E7.A0.81">兼容于ASCII和ISO标准的Unicode编码</h3>
<p>Unicode is fully compatible with the International Standard ISO/IEC 10646-1; 1993, which is a subset of ISO 10646.</p>
<p>Several encoding standards (including UTF-8, UTF-16 and ISO UCS-2) are used to physically represent Unicode as actual bits.</p>
<p>The UTF-8 encoding of Unicode is compatible with ASCII characters and is supported by many programs. The first 128 Unicode characters correspond to the ASCII characters and have the same byte value. The Unicode characters U+0020 through U+007E are equivalent to the ASCII characters 0x20 through 0x7E. Unlike ASCII, which supports the Latin alphabet and uses a 7-bit character set, UTF-8 uses between one and four octets for each character ("octet" meaning a byte, or 8 bits.) This allows for several million characters. An alternative encoding standard, UTF-16, uses two octets to represent Unicode characters. An escape sequence allows UTF-16 to represent the whole Unicode range by using four octets. The ISO UCS-2 (Universal Character Set) uses two octets.</p>
<p>JavaScript and Navigator support for UTF-8/Unicode means you can use non-Latin, international, and localized characters, plus special technical symbols in JavaScript programs. Unicode provides a standard way to encode multilingual text. Since the UTF-8 encoding of Unicode is compatible with ASCII, programs can use ASCII characters. You can use non-ASCII Unicode characters in the comments, string literals, identifiers, and regular expressions of JavaScript.</p>
<h3 id="Unicode.E8.BD.AC.E4.B9.89.E5.BA.8F.E5.88.97">Unicode转义序列</h3>
<p>You can use the Unicode escape sequence in string literals, regular expressions, and identifiers. The escape sequence consists of six ASCII characters: \u and a four-digit hexadecimal number. For example, \u00A9 represents the copyright symbol. Every Unicode escape sequence in JavaScript is interpreted as one character.</p>
<p>The following code returns the copyright symbol and the string "Netscape Communications".</p>
<pre class="brush: js">
var x = "\u00A9 Netscape Communications";</pre>
<p>The following table lists frequently used special characters and their Unicode value.</p>
<table class="standard-table">
  <caption style="text-align: left;">
    Table 2.2 Unicode values for special characters</caption>
  <thead>
    <tr>
      <th scope="col">Category</th>
      <th scope="col">Unicode value</th>
      <th scope="col">Name</th>
      <th scope="col">Format name</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td rowspan="4">White space values</td>
      <td>\u0009</td>
      <td>Tab</td>
      <td>&lt;TAB&gt;</td>
    </tr>
    <tr>
      <td>\u000B</td>
      <td>Vertical Tab</td>
      <td>&lt;VT&gt;</td>
    </tr>
    <tr>
      <td>\u000C</td>
      <td>Form Feed</td>
      <td>&lt;FF&gt;</td>
    </tr>
    <tr>
      <td>\u0020</td>
      <td>Space</td>
      <td>&lt;SP&gt;</td>
    </tr>
    <tr>
      <td rowspan="2">Line terminator values</td>
      <td>\u000A</td>
      <td>Line Feed</td>
      <td>&lt;LF&gt;</td>
    </tr>
    <tr>
      <td>\u000D</td>
      <td>Carriage Return</td>
      <td>&lt;CR&gt;</td>
    </tr>
    <tr>
      <td rowspan="5">Additional Unicode escape sequence values</td>
      <td>\u0008</td>
      <td>Backspace</td>
      <td>&lt;BS&gt;</td>
    </tr>
    <tr>
      <td>\u0009</td>
      <td>Horizontal Tab</td>
      <td>&lt;HT&gt;</td>
    </tr>
    <tr>
      <td>\u0022</td>
      <td>Double Quote</td>
      <td>"</td>
    </tr>
    <tr>
      <td>\u0027</td>
      <td>Single Quote</td>
      <td>'</td>
    </tr>
    <tr>
      <td>\u005C</td>
      <td>Backslash</td>
      <td>\</td>
    </tr>
  </tbody>
</table>
<p>The JavaScript use of the Unicode escape sequence is different from Java. In JavaScript, the escape sequence is never interpreted as a special character first. For example, a line terminator escape sequence inside a string does not terminate the string before it is interpreted by the function. JavaScript ignores any escape sequence if it is used in comments. In Java, if an escape sequence is used in a single comment line, it is interpreted as an Unicode character. For a string literal, the Java compiler interprets the escape sequences first. For example, if a line terminator escape character (e.g., \u000A) is used in Java, it terminates the string literal. In Java, this leads to an error, because line terminators are not allowed in string literals. You must use \n for a line feed in a string literal. In JavaScript, the escape sequence works the same way as \n.</p>
<h3 id="JavaScript.E6.96.87.E4.BB.B6.E4.B8.AD.E7.9A.84Unicode.E5.AD.97.E7.AC.A6">JavaScript文件中的Unicode字符</h3>
<p>Earlier versions of <a href="/zh-CN/docs/Gecko" title="zh-CN/docs/Gecko">Gecko</a> assumed the Latin-1 character encoding for JavaScript files loaded from XUL. Starting with Gecko 1.8, the character encoding is inferred from the XUL file's encoding. Please see <a href="/zh-CN/docs/International_characters_in_XUL_JavaScript" title="zh-CN/docs/International_characters_in_XUL_JavaScript">International characters in XUL JavaScript</a> for more information.</p>
<h3 id=".E7.94.A8Unicode.E7.BC.96.E7.A0.81.E6.98.BE.E7.A4.BA.E5.AD.97.E7.AC.A6">用Unicode编码显示字符</h3>
<p>You can use Unicode to display the characters in different languages or technical symbols. For characters to be displayed properly, a client such as Mozilla Firefox or Netscape needs to support Unicode. Moreover, an appropriate Unicode font must be available to the client, and the client platform must support Unicode. Often, Unicode fonts do not display all the Unicode characters. Some platforms, such as Windows 95, provide partial support for Unicode.</p>
<p>To receive non-ASCII character input, the client needs to send the input as Unicode. Using a standard enhanced keyboard, the client cannot easily input the additional characters supported by Unicode. Sometimes, the only way to input Unicode characters is by using Unicode escape sequences.</p>
<p>For more information on Unicode, see the <a class="external" href="http://www.unicode.org/">Unicode Home Page</a> and The Unicode Standard, Version 2.0, published by Addison-Wesley, 1996.</p>
<h2 id=".E5.A4.96.E9.83.A8.E5.8F.82.E8.80.83.E8.B5.84.E6.BA.90">外部参考资源</h2>
<ul>
  <li><a class="external" href="http://0xcc.net/jsescape/" title="Text Escaping and Unescaping in JavaScript">Text Escaping and Unescaping in JavaScript</a> – an utility to convert characters in JavaScript unicode values</li>
</ul>
<div>
  {{autoPreviousNext("JSGChapters")}}</div>
恢复到这个版本