diff options
author | Irvin <irvinfly@gmail.com> | 2022-02-16 02:02:49 +0800 |
---|---|---|
committer | Irvin <irvinfly@gmail.com> | 2022-02-16 02:35:54 +0800 |
commit | 01b0e12ba27b5069248fd09235e9a7143915ee30 (patch) | |
tree | 0e9edf538dc3fa3331e1dbb79239b58186765f86 /files/zh-cn | |
parent | 6ca84f1794af830ada9736d7289ce29aabb04ca3 (diff) | |
download | translated-content-01b0e12ba27b5069248fd09235e9a7143915ee30.tar.gz translated-content-01b0e12ba27b5069248fd09235e9a7143915ee30.tar.bz2 translated-content-01b0e12ba27b5069248fd09235e9a7143915ee30.zip |
remove `notranslate` class in zh-CN
Diffstat (limited to 'files/zh-cn')
198 files changed, 1409 insertions, 1409 deletions
diff --git a/files/zh-cn/web/javascript/a_re-introduction_to_javascript/index.html b/files/zh-cn/web/javascript/a_re-introduction_to_javascript/index.html index 7c567f3902..b49d5c9024 100644 --- a/files/zh-cn/web/javascript/a_re-introduction_to_javascript/index.html +++ b/files/zh-cn/web/javascript/a_re-introduction_to_javascript/index.html @@ -63,7 +63,7 @@ translation_of: Web/JavaScript/A_re-introduction_to_JavaScript <p>根据语言规范,JavaScript 采用“遵循 IEEE 754 标准的双精度 64 位格式”("double-precision 64-bit format IEEE 754 values")表示数字。——在JavaScript(除了{{jsxref("BigInt")}})当中,<strong>并不存在整数/整型(Integer)。</strong>因此在处理如下的场景时候,您一定要小心:</p> -<pre class="notranslate">console.log(3 / 2); // 1.5,<em>not</em> 1 +<pre>console.log(3 / 2); // 1.5,<em>not</em> 1 console.log(Math.floor(3 / 2)); // 1 </pre> @@ -71,67 +71,67 @@ console.log(Math.floor(3 / 2)); // 1 <p>当然,您也需要小心这种情况:</p> -<pre class="brush: js notranslate">0.1 + 0.2 = 0.30000000000000004 +<pre class="brush: js">0.1 + 0.2 = 0.30000000000000004 </pre> <p>在具体实现时,整数值通常被视为32位整型变量,在个别实现(如某些浏览器)中也以32位整型变量的形式进行存储,直到它被用于执行某些32位整型不支持的操作,这是为了便于进行位操作。</p> <p>JavaScript 支持标准的<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators">算术运算符</a>,包括加法、减法、取模(或取余)等等。还有一个之前没有提及的内置对象 {{jsxref("Math")}}(数学对象),用以处理更多的高级数学函数和常数:</p> -<pre class="brush: js notranslate">Math.sin(3.5); +<pre class="brush: js">Math.sin(3.5); var circumference = 2 * Math.PI * r; </pre> <p>你可以使用内置函数 {{jsxref("Global_Objects/parseInt", "parseInt()")}} 将字符串转换为整型。该函数的第二个可选参数表示字符串所表示数字的基(进制):</p> -<pre class="brush: js notranslate">parseInt("123", 10); // 123 +<pre class="brush: js">parseInt("123", 10); // 123 parseInt("010", 10); // 10 </pre> <p>一些老版本的浏览器会将首字符为“0”的字符串当做八进制数字,2013 年以前的 JavaScript 实现会返回一个意外的结果:</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">parseInt("010"); // 8 +<pre class="brush: js line-numbers language-js"><code class="language-js">parseInt("010"); // 8 parseInt("0x10"); // 16</code></pre> <p>这是因为字符串以数字 0 开头,{{jsxref("Global_Objects/parseInt", "parseInt()")}}函数会把这样的字符串视作八进制数字;同理,0x开头的字符串则视为十六进制数字。</p> <p>如果想把一个二进制数字字符串转换成整数值,只要把第二个参数设置为 2 就可以了:</p> -<pre class="brush: js notranslate">parseInt("11", 2); // 3 +<pre class="brush: js">parseInt("11", 2); // 3 </pre> <p>JavaScript 还有一个类似的内置函数 {{jsxref("Global_Objects/parseFloat", "parseFloat()")}},用以解析浮点数字符串,与{{jsxref("Global_Objects/parseInt", "parseInt()")}}不同的地方是,<code>parseFloat()</code> 只应用于解析十进制数字。</p> <p>一元运算符 + 也可以把数字字符串转换成数值:</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">+ "42"; // 42 +<pre class="brush: js line-numbers language-js"><code class="language-js">+ "42"; // 42 + "010"; // 10 + "0x10"; // 16</code></pre> <p>如果给定的字符串不存在数值形式,函数会返回一个特殊的值 {{jsxref("NaN")}}(Not a Number 的缩写):</p> -<pre class="brush: js notranslate">parseInt("hello", 10); // NaN +<pre class="brush: js">parseInt("hello", 10); // NaN </pre> <p>要小心NaN:如果把 <code>NaN</code> 作为参数进行任何数学运算,结果也会是 <code>NaN</code>:</p> -<pre class="brush: js notranslate">NaN + 5; //NaN +<pre class="brush: js">NaN + 5; //NaN </pre> <p>可以使用内置函数 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/isNaN"><code>isNaN()</code></a> 来判断一个变量是否为 <code>NaN</code>:</p> -<pre class="brush: js notranslate">isNaN(NaN); // true +<pre class="brush: js">isNaN(NaN); // true </pre> <p>JavaScript 还有两个特殊值:<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Infinity"><code>Infinity</code></a>(正无穷)和 <code>-Infinity</code>(负无穷):</p> -<pre class="brush: js notranslate">1 / 0; // Infinity +<pre class="brush: js">1 / 0; // Infinity -1 / 0; // -Infinity </pre> <p>可以使用内置函数 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/isFinite"><code>isFinite()</code></a> 来判断一个变量是否是一个有穷数, 如果类型为<code>Infinity</code>, <code>-Infinity</code> 或 <code>NaN则返回false</code>:</p> -<pre class="brush: js notranslate">isFinite(1/0); // false +<pre class="brush: js">isFinite(1/0); // false isFinite(Infinity); // false isFinite(-Infinity); // false isFinite(NaN); // false @@ -153,12 +153,12 @@ Number.isFinite("0"); // false</pre> <p>通过访问字符串的 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/length"><code>length</code></a>(编码单元的个数)属性,可以得到它的长度。</p> -<pre class="brush: js notranslate">"hello".length; // 5 +<pre class="brush: js">"hello".length; // 5 </pre> <p>这是我们第一次碰到 JavaScript 对象。我们有没有提过你可以像 {{jsxref("Object", "object", "", 1)}} 一样使用字符串?是的,字符串也有 {{jsxref("String", "methods", "#Methods", 1)}}(方法)能让你操作字符串和获取字符串的信息。</p> -<pre class="brush: js notranslate">"hello".charAt(0); // "h" +<pre class="brush: js">"hello".charAt(0); // "h" "hello, world".replace("world", "mars"); // "hello, mars" "hello".toUpperCase(); // "HELLO" </pre> @@ -176,7 +176,7 @@ Number.isFinite("0"); // false</pre> <p>也可以使用 <code>Boolean()</code> 函数进行显式转换:</p> -<pre class="brush: js notranslate">Boolean(''); // false +<pre class="brush: js">Boolean(''); // false Boolean(234); // true </pre> @@ -190,12 +190,12 @@ Boolean(234); // true <p><code><strong>let</strong></code> 语句声明一个块级作用域的本地变量,并且可选的将其初始化为一个值。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">let a; +<pre class="brush: js line-numbers language-js"><code class="language-js">let a; let name = 'Simon';</code></pre> <p>下面是使用 <code><strong>let</strong></code> 声明变量作用域的例子:</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">// myLetVariable 在这里 *不能* 被引用 +<pre class="brush: js line-numbers language-js"><code class="language-js">// myLetVariable 在这里 *不能* 被引用 for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) { // myLetVariable 只能在这里引用 @@ -205,18 +205,18 @@ for (let myLetVariable = 0; myLetVariable < 5; myLetVariable++) { <p><code><strong>const</strong></code> 允许声明一个不可变的常量。这个常量在定义域内总是可见的。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">const Pi = 3.14; // 设置 Pi 的值 +<pre class="brush: js line-numbers language-js"><code class="language-js">const Pi = 3.14; // 设置 Pi 的值 Pi = 1; // 将会抛出一个错误因为你改变了一个常量的值。</code></pre> <p><code><strong>var</strong></code> 是最常见的声明变量的关键字。它没有其他两个关键字的种种限制。这是因为它是传统上在 JavaScript 声明变量的唯一方法。使用 <strong><code>var</code></strong> 声明的变量在它所声明的整个函数都是可见的。</p> -<pre class="brush: js notranslate">var a; +<pre class="brush: js">var a; var name = "simon"; </pre> <p>一个使用 <strong><code>var</code> </strong>声明变量的语句块的例子:</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">// myVarVariable在这里 *能* 被引用 +<pre class="brush: js line-numbers language-js"><code class="language-js">// myVarVariable在这里 *能* 被引用 for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) { // myVarVariable 整个</code>函数<code class="language-js">中都能被引用 @@ -232,19 +232,19 @@ for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) { <p>JavaScript的算术操作符包括 <code>+</code>、<code>-</code>、<code>*</code>、<code>/</code> 和 <code>%</code> ——求余(<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#求余_%28%29">与模运算相同</a>)。赋值使用 <code>=</code> 运算符,此外还有一些复合运算符,如 <code>+=</code> 和 <code>-=</code>,它们等价于 <code>x = x <em>operator</em> y</code>。</p> -<pre class="brush: js notranslate">x += 5; // 等价于 x = x + 5; +<pre class="brush: js">x += 5; // 等价于 x = x + 5; </pre> <p>可以使用 <code>++</code> 和 <code>--</code> 分别实现变量的自增和自减。两者都可以作为前缀或后缀操作符使用。</p> <p><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#.E5.8A.A0.E6.B3.95_(.2B)"><code>+</code> 操作符</a>还可以用来连接字符串:</p> -<pre class="brush: js notranslate">"hello" + " world"; // hello world +<pre class="brush: js">"hello" + " world"; // hello world </pre> <p>如果你用一个字符串加上一个数字(或其他值),那么操作数都会被首先转换为字符串。如下所示:</p> -<pre class="brush: js notranslate">"3" + 4 + 5; // 345 +<pre class="brush: js">"3" + 4 + 5; // 345 3 + 4 + "5"; // 75 </pre> @@ -252,13 +252,13 @@ for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) { <p>JavaScript 中的<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">比较操作</a>使用 <code><</code>、<code>></code>、<code><=</code> 和 <code>>=</code>,这些运算符对于数字和字符串都通用。相等的比较稍微复杂一些。由两个“<code>=</code>(等号)”组成的相等运算符有类型自适应的功能,具体例子如下:</p> -<pre class="brush: js notranslate">123 == "123" // true +<pre class="brush: js">123 == "123" // true 1 == true; // true </pre> <p>如果在比较前不需要自动类型转换,应该使用由三个“<code>=</code>(等号)”组成的相等运算符:</p> -<pre class="brush: js notranslate">1 === true; //false +<pre class="brush: js">1 === true; //false 123 === "123"; // false </pre> @@ -270,7 +270,7 @@ for (var myVarVariable = 0; myVarVariable < 5; myVarVariable++) { <p>JavaScript 的控制结构与其他类 C 语言类似。可以使用 <code>if</code> 和 <code>else</code> 来定义条件语句,还可以连起来使用:</p> -<pre class="brush: js notranslate">var name = "kittens"; +<pre class="brush: js">var name = "kittens"; if (name == "puppies") { name += "!"; } else if (name == "kittens") { @@ -283,7 +283,7 @@ name == "kittens!!"; // true <p>JavaScript 支持 <code>while</code> 循环和 <code>do-while</code> 循环。前者适合常见的基本循环操作,如果需要循环体至少被执行一次则可以使用 <code>do-while</code>:</p> -<pre class="brush: js notranslate">while (true) { +<pre class="brush: js">while (true) { // 一个无限循环! } @@ -295,41 +295,41 @@ do { <p>JavaScript 的 <code><a href="/zh-CN/docs/Web/JavaScript/Reference/Statements/for">for</a></code> 循环与 C 和 Java 中的相同:使用时可以在一行代码中提供控制信息。</p> -<pre class="brush: js notranslate">for (var i = 0; i < 5; i++) { +<pre class="brush: js">for (var i = 0; i < 5; i++) { // 将会执行五次 } </pre> <p>JavaScript 也还包括其他两种重要的 for 循环: <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for</code>...<code>of</code></a></p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">for (let value of array) { +<pre class="brush: js line-numbers language-js"><code class="language-js">for (let value of array) { // do something with value }</code></pre> <p>和 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for</code>...<code>in</code></a> :</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">for (let property in object) { +<pre class="brush: js line-numbers language-js"><code class="language-js">for (let property in object) { // do something with object property }</code></pre> <p><code>&&</code> 和 <code>||</code> 运算符使用短路逻辑(short-circuit logic),是否会执行第二个语句(操作数)取决于第一个操作数的结果。在需要访问某个对象的属性时,使用这个特性可以事先检测该对象是否为空:</p> -<pre class="brush: js notranslate">var name = o && o.getName(); +<pre class="brush: js">var name = o && o.getName(); </pre> <p>或用于缓存值(当错误值无效时):</p> -<pre class="brush: js notranslate">var name = cachedName || (cachedName = getName()); +<pre class="brush: js">var name = cachedName || (cachedName = getName()); </pre> <p>类似地,JavaScript 也有一个用于条件表达式的三元操作符:</p> -<pre class="brush: js notranslate">var allowed = (age > 18) ? "yes" : "no"; +<pre class="brush: js">var allowed = (age > 18) ? "yes" : "no"; </pre> <p>在需要多重分支时可以使用基于一个数字或字符串的 <code>switch</code> 语句:</p> -<pre class="brush: js notranslate">switch(action) { +<pre class="brush: js">switch(action) { case 'draw': drawIt(); break; @@ -343,7 +343,7 @@ do { <p>如果你不使用 <code>break</code> 语句,JavaScript 解释器将会执行之后 <code>case</code> 中的代码。除非是为了调试,一般你并不需要这个特性,所以大多数时候不要忘了加上 <code>break。</code></p> -<pre class="brush: js notranslate">switch(a) { +<pre class="brush: js">switch(a) { case 1: // 继续向下 case 2: eatIt(); @@ -355,7 +355,7 @@ do { <p><code>default</code> 语句是可选的。<code>switch</code> 和 <code>case</code> 都可以使用需要运算才能得到结果的表达式;在 <code>switch</code> 的表达式和 <code>case</code> 的表达式是使用 <code>===</code> 严格相等运算符进行比较的:</p> -<pre class="brush: js notranslate">switch(1 + 3){ +<pre class="brush: js">switch(1 + 3){ case 2 + 2: yay(); break; @@ -382,19 +382,19 @@ do { <p>有两种简单方法可以创建一个空对象:</p> -<pre class="brush: js notranslate">var obj = new Object(); +<pre class="brush: js">var obj = new Object(); </pre> <p>和:</p> -<pre class="brush: js notranslate">var obj = {}; +<pre class="brush: js">var obj = {}; </pre> <p>这两种方法在语义上是相同的。第二种更方便的方法叫作“对象字面量(object literal)”法。这种也是 JSON 格式的核心语法,一般我们优先选择第二种方法。</p> <p>“对象字面量”也可以用来在对象实例中定义一个对象:</p> -<pre class="brush: js notranslate">var obj = { +<pre class="brush: js">var obj = { name: "Carrot", _for: "Max",//'for' 是保留字之一,使用'_for'代替 details: { @@ -406,13 +406,13 @@ do { <p>对象的属性可以通过链式(chain)表示方法进行访问:</p> -<pre class="brush: js notranslate">obj.details.color; // orange +<pre class="brush: js">obj.details.color; // orange obj["details"]["size"]; // 12 </pre> <p>下面的例子创建了一个对象原型,<code><strong>Person</strong></code>,和这个原型的实例,<strong><code>You</code></strong>。</p> -<pre class="brush: js notranslate">function Person(name, age) { +<pre class="brush: js">function Person(name, age) { this.name = name; this.age = age; } @@ -425,14 +425,14 @@ var You = new Person('You', 24); <p>完成创建后,对象属性可以通过如下两种方式进行赋值和访问:</p> -<pre class="brush: js notranslate">// 点表示法(dot notation) +<pre class="brush: js">// 点表示法(dot notation) obj.name = 'Simon'; var name = obj.name; </pre> <p>和:</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">// 括号表示法(bracket notation) +<pre class="brush: js line-numbers language-js"><code class="language-js">// 括号表示法(bracket notation) obj['name'] = 'Simon'; var name = obj['name']; // can use a variable to define a key @@ -441,7 +441,7 @@ obj[user] = prompt('what is its value?')</code></pre> <p>这两种方法在语义上也是相同的。第二种方法的优点在于属性的名称被看作一个字符串,这就意味着它可以在运行时被计算,缺点在于这样的代码有可能无法在后期被解释器优化。它也可以被用来访问某些以<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Keywords">预留关键字</a>作为名称的属性的值:</p> -<pre class="brush: js notranslate">obj.for = 'Simon'; // 语法错误,因为 for 是一个预留关键字 +<pre class="brush: js">obj.for = 'Simon'; // 语法错误,因为 for 是一个预留关键字 obj["for"] = 'Simon'; // 工作正常 </pre> @@ -461,7 +461,7 @@ obj["for"] = 'Simon'; // 工作正常 <p>创建数组的传统方法是:</p> -<pre class="brush: js notranslate">var a = new Array(); +<pre class="brush: js">var a = new Array(); a[0] = "dog"; a[1] = "cat"; a[2] = "hen"; @@ -470,13 +470,13 @@ a.length; // 3 <p>使用数组字面量(array literal)法更加方便:</p> -<pre class="brush: js notranslate">var a = ["dog", "cat", "hen"]; +<pre class="brush: js">var a = ["dog", "cat", "hen"]; a.length; // 3 </pre> <p>注意,<code>Array.length </code>并不总是等于数组中元素的个数,如下所示:</p> -<pre class="brush: js notranslate">var a = ["dog", "cat", "hen"]; +<pre class="brush: js">var a = ["dog", "cat", "hen"]; a[100] = "fox"; a.length; // 101 </pre> @@ -485,40 +485,40 @@ a.length; // 101 <p>如果试图访问一个不存在的数组索引,会得到 <code>undefined</code>:</p> -<pre class="brush: js notranslate">typeof(a[90]); // undefined +<pre class="brush: js">typeof(a[90]); // undefined </pre> <p>可以通过如下方式遍历一个数组:</p> -<pre class="brush: js notranslate">for (var i = 0; i < a.length; i++) { +<pre class="brush: js">for (var i = 0; i < a.length; i++) { // Do something with a[i] } </pre> <p>ES2015 引入了更加简洁的 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of"><code>for</code>...<code>of</code></a> 循环,可以用它来遍历可迭代对象,例如数组:</p> -<pre class="brush: js notranslate">for (const currentValue of a) { +<pre class="brush: js">for (const currentValue of a) { // Do something with currentValue } </pre> <p>遍历数组的另一种方法是使用 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> 循环, 然而这并不是遍历数组元素而是数组的索引。注意,如果哪个家伙直接向 <code>Array.prototype</code> 添加了新的属性,使用这样的循环这些属性也同样会被遍历。所以并不推荐使用这种方法遍历数组:</p> -<pre class="brush: js notranslate">for (var i in a) { +<pre class="brush: js">for (var i in a) { // 操作 a[i] } </pre> <p>ECMAScript 5 增加了另一个遍历数组的方法,<code><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach">forEach()</a></code>:</p> -<pre class="brush: js notranslate">["dog", "cat", "hen"].forEach(function(currentValue, index, array) { +<pre class="brush: js">["dog", "cat", "hen"].forEach(function(currentValue, index, array) { // 操作 currentValue 或者 array[index] }); </pre> <p>如果想在数组后追加元素,只需要:</p> -<pre class="brush: js notranslate">a.push(item);</pre> +<pre class="brush: js">a.push(item);</pre> <p>除了 <code>forEach()</code> 和 <code>push()</code>,Array(数组)类还自带了许多方法。建议查看 <a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array">Array 方法的完整文档</a>。</p> @@ -591,7 +591,7 @@ a.length; // 101 <p>学习 JavaScript 最重要的就是要理解对象和函数两个部分。最简单的函数就像下面这个这么简单:</p> -<pre class="brush: js notranslate">function add(x, y) { +<pre class="brush: js">function add(x, y) { var total = x + y; return total; } @@ -601,19 +601,19 @@ a.length; // 101 <p>已命名的参数更像是一个指示而没有其他作用。如果调用函数时没有提供足够的参数,缺少的参数会被 <code>undefined</code> 替代。</p> -<pre class="brush: js notranslate">add(); // NaN +<pre class="brush: js">add(); // NaN // 不能在 undefined 对象上进行加法操作 </pre> <p>你还可以传入多于函数本身需要参数个数的参数:</p> -<pre class="brush: js notranslate">add(2, 3, 4); // 5 +<pre class="brush: js">add(2, 3, 4); // 5 // 将前两个值相加,4 被忽略了 </pre> <p>这看上去有点蠢。函数实际上是访问了函数体中一个名为 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions_and_function_scope/arguments"><code>arguments</code></a> 的内部对象,这个对象就如同一个类似于数组的对象一样,包括了所有被传入的参数。让我们重写一下上面的函数,使它可以接收任意个数的参数:</p> -<pre class="brush: js notranslate">function add() { +<pre class="brush: js">function add() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; @@ -626,7 +626,7 @@ add(2, 3, 4, 5); // 14 <p>这跟直接写成 <code>2 + 3 + 4 + 5</code> 也没什么区别。我们还是创建一个求平均数的函数吧:</p> -<pre class="brush: js notranslate">function avg() { +<pre class="brush: js">function avg() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; @@ -637,7 +637,7 @@ avg(2, 3, 4, 5); // 3.5</pre> <p>这个就有用多了,但是却有些冗长。为了使代码变短一些,我们可以使用<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Rest_parameters">剩余参数</a>来替换arguments的使用。在这方法中,我们可以传递任意数量的参数到函数中同时尽量减少我们的代码。这个<strong>剩余参数操作符</strong>在函数中以:<strong>...variable</strong> 的形式被使用,它将包含在调用函数时使用的未捕获整个参数列表到这个变量中。我们同样也可以将 <strong>for</strong> 循环替换为 <strong>for...of </strong> 循环来返回我们变量的值。</p> -<pre class="brush: js notranslate">function avg(...args) { +<pre class="brush: js">function avg(...args) { var sum = 0; for (let value of args) { sum += value; @@ -654,7 +654,7 @@ avg(2, 3, 4, 5); // 3.5 <p>需要注意的是,无论“剩余参数操作符”被放置到函数声明的哪里,它都会把除了自己之前的所有参数存储起来。比如函数:function avg(<strong>firstValue</strong>, ...args) 会把传入函数的第一个值存入 <strong>firstValue</strong>,其他的参数存入 <strong>args</strong>。这是虽然一个很有用的语言特性,却也会带来新的问题。<code>avg()</code> 函数只接受逗号分开的参数列表 -- 但是如果你想要获取一个数组的平均值怎么办?一种方法是将函数按照如下方式重写:</p> </div> -<pre class="brush: js notranslate">function avgArray(arr) { +<pre class="brush: js">function avgArray(arr) { var sum = 0; for (var i = 0, j = arr.length; i < j; i++) { sum += arr[i]; @@ -666,7 +666,7 @@ avgArray([2, 3, 4, 5]); // 3.5 <p>但如果能重用我们已经创建的那个函数不是更好吗?幸运的是 JavaScript 允许你通过任意函数对象的 <code><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/apply">apply()</a></code> 方法来传递给它一个数组作为参数列表。</p> -<pre class="brush: js notranslate">avg.apply(null, [2, 3, 4, 5]); // 3.5 +<pre class="brush: js">avg.apply(null, [2, 3, 4, 5]); // 3.5 </pre> <p>传给 <code>apply()</code> 的第二个参数是一个数组,它将被当作 <code>avg()</code> 的参数列表使用,至于第一个参数 <code>null</code>,我们将在后面讨论。这也正说明了一个事实——函数也是对象。</p> @@ -679,7 +679,7 @@ avgArray([2, 3, 4, 5]); // 3.5 <p>JavaScript 允许你创建匿名函数:</p> -<pre class="brush: js notranslate">var avg = function() { +<pre class="brush: js">var avg = function() { var sum = 0; for (var i = 0, j = arguments.length; i < j; i++) { sum += arguments[i]; @@ -690,7 +690,7 @@ avgArray([2, 3, 4, 5]); // 3.5 <p>这个函数在语义上与 <code>function avg()</code> 相同。你可以在代码中的任何地方定义这个函数,就像写普通的表达式一样。基于这个特性,有人发明出一些有趣的技巧。与 C 中的块级作用域类似,下面这个例子隐藏了局部变量:</p> -<pre class="brush: js notranslate">var a = 1; +<pre class="brush: js">var a = 1; var b = 2; (function() { var b = 3; @@ -703,7 +703,7 @@ b; // 2 <p>JavaScript 允许以递归方式调用函数。递归在处理树形结构(比如浏览器 <a href="https://developer.mozilla.org/zh-CN/docs/Web/API/Document_Object_Model">DOM</a>)时非常有用。</p> -<pre class="brush: js notranslate">function countChars(elm) { +<pre class="brush: js">function countChars(elm) { if (elm.nodeType == 3) { // 文本节点 return elm.nodeValue.length; } @@ -717,7 +717,7 @@ b; // 2 <p>这里需要说明一个潜在问题——既然匿名函数没有名字,那该怎么递归调用它呢?在这一点上,JavaScript 允许你命名这个函数表达式。你可以命名立即调用的函数表达式(IIFE——Immediately Invoked Function Expression),如下所示:</p> -<pre class="brush: js notranslate">var charsInBody = (function counter(elm) { +<pre class="brush: js">var charsInBody = (function counter(elm) { if (elm.nodeType == 3) { // 文本节点 return elm.nodeValue.length; } @@ -739,7 +739,7 @@ b; // 2 <p>在经典的面向对象语言中,对象是指数据和在这些数据上进行的操作的集合。与 C++ 和 Java 不同,JavaScript 是一种基于原型的编程语言,并没有 class 语句,而是把函数用作类。那么让我们来定义一个人名对象,这个对象包括人的姓和名两个域(field)。名字的表示有两种方法:“名 姓(First Last)”或“姓, 名(Last, First)”。使用我们前面讨论过的函数和对象概念,可以像这样完成定义:</p> -<pre class="brush: js notranslate">function makePerson(first, last) { +<pre class="brush: js">function makePerson(first, last) { return { first: first, last: last @@ -758,7 +758,7 @@ personFullNameReversed(s); // "Willison, Simon"</pre> <p>上面的写法虽然可以满足要求,但是看起来很麻烦,因为需要在全局命名空间中写很多函数。既然函数本身就是对象,如果需要使一个函数隶属于一个对象,那么不难得到:</p> -<pre class="brush: js notranslate">function makePerson(first, last) { +<pre class="brush: js">function makePerson(first, last) { return { first: first, last: last, @@ -776,7 +776,7 @@ s.fullNameReversed(); // Willison, Simon</pre> <p>上面的代码里有一些我们之前没有见过的东西:关键字 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a>。当使用在函数中时,<code>this</code> 指代当前的对象,也就是调用了函数的对象。如果在一个对象上使用<a href="https://developer.mozilla.org/en/JavaScript/Reference/Operators/Member_Operators">点或者方括号</a>来访问属性或方法,这个对象就成了 <code>this</code>。如果并没有使用“点”运算符调用某个对象,那么 <code>this</code> 将指向全局对象(global object)。这是一个经常出错的地方。例如:</p> -<pre class="brush: js notranslate">s = makePerson("Simon", "Willison"); +<pre class="brush: js">s = makePerson("Simon", "Willison"); var fullName = s.fullName; fullName(); // undefined undefined </pre> @@ -785,7 +785,7 @@ fullName(); // undefined undefined <p>下面使用关键字 <code>this</code> 改进已有的 <code>makePerson</code>函数:</p> -<pre class="brush: js notranslate">function Person(first, last) { +<pre class="brush: js">function Person(first, last) { this.first = first; this.last = last; this.fullName = function() { @@ -804,7 +804,7 @@ var s = new Person("Simon", "Willison"); <p>我们的 Person 对象现在已经相当完善了,但还有一些不太好的地方。每次我们创建一个 Person 对象的时候,我们都在其中创建了两个新的函数对象——如果这个代码可以共享不是更好吗?</p> -<pre class="brush: js notranslate">function personFullName() { +<pre class="brush: js">function personFullName() { return this.first + ' ' + this.last; } function personFullNameReversed() { @@ -820,7 +820,7 @@ function Person(first, last) { <p>这种写法的好处是,我们只需要创建一次方法函数,在构造函数中引用它们。那是否还有更好的方法呢?答案是肯定的。</p> -<pre class="brush: js notranslate">function Person(first, last) { +<pre class="brush: js">function Person(first, last) { this.first = first; this.last = last; } @@ -836,7 +836,7 @@ Person.prototype.fullNameReversed = function() { <p>这个特性功能十分强大,JavaScript 允许你在程序中的任何时候修改原型(prototype)中的一些东西,也就是说你可以在运行时(runtime)给已存在的对象添加额外的方法:</p> -<pre class="brush: js notranslate">s = new Person("Simon", "Willison"); +<pre class="brush: js">s = new Person("Simon", "Willison"); s.firstNameCaps(); // TypeError on line 1: s.firstNameCaps is not a function Person.prototype.firstNameCaps = function() { @@ -847,7 +847,7 @@ s.firstNameCaps(); // SIMON <p>有趣的是,你还可以给 JavaScript 的内置函数原型(prototype)添加东西。让我们给 <code>String</code> 添加一个方法用来返回逆序的字符串:</p> -<pre class="brush: js notranslate">var s = "Simon"; +<pre class="brush: js">var s = "Simon"; s.reversed(); // TypeError on line 1: s.reversed is not a function String.prototype.reversed = function() { @@ -862,12 +862,12 @@ s.reversed(); // nomiS <p>定义新方法也可以在字符串字面量上用(string literal)。</p> -<pre class="brush: js notranslate">"This can now be reversed".reversed(); // desrever eb won nac sihT +<pre class="brush: js">"This can now be reversed".reversed(); // desrever eb won nac sihT </pre> <p>正如我前面提到的,原型组成链的一部分。那条链的根节点是 <code>Object.prototype</code>,它包括 <code>toString()</code> 方法——将对象转换成字符串时调用的方法。这对于调试我们的 <code>Person</code> 对象很有用:</p> -<pre class="brush: js notranslate">var s = new Person("Simon", "Willison"); +<pre class="brush: js">var s = new Person("Simon", "Willison"); s; // [object Object] Person.prototype.toString = function() { @@ -878,7 +878,7 @@ s.toString(); // <Person: Simon Willison> <p>你是否还记得之前我们说的 <code>avg.apply()</code> 中的第一个参数 <code>null</code>?现在我们可以回头看看这个东西了。<code>apply()</code> 的第一个参数应该是一个被当作 <code>this</code> 来看待的对象。下面是一个 <code>new</code> 方法的简单实现:</p> -<pre class="brush: js notranslate">function trivialNew(constructor, ...args) { +<pre class="brush: js">function trivialNew(constructor, ...args) { var o = {}; // 创建一个对象 constructor.apply(o, args); return o; @@ -889,15 +889,15 @@ s.toString(); // <Person: Simon Willison> <p>因此,调用</p> -<pre class="brush: js notranslate">var bill = trivialNew(Person, "William", "Orange");</pre> +<pre class="brush: js">var bill = trivialNew(Person, "William", "Orange");</pre> <p>可认为和调用如下语句是等效的</p> -<pre class="brush: js notranslate">var bill = new Person("William", "Orange");</pre> +<pre class="brush: js">var bill = new Person("William", "Orange");</pre> <p><code>apply()</code> 有一个姐妹函数,名叫 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call"><code>call</code></a>,它也可以允许你设置 <code>this</code>,但它带有一个扩展的参数列表而不是一个数组。</p> -<pre class="brush: js notranslate">function lastNameCaps() { +<pre class="brush: js">function lastNameCaps() { return this.last.toUpperCase(); } var s = new Person("Simon", "Willison"); @@ -911,7 +911,7 @@ s.lastNameCaps(); <p>JavaScript 允许在一个函数内部定义函数,这一点我们在之前的 <code>makePerson()</code> 例子中也见过。关于 JavaScript 中的嵌套函数,一个很重要的细节是,它们可以访问父函数作用域中的变量:</p> -<pre class="brush: js notranslate">function parentFunc() { +<pre class="brush: js">function parentFunc() { var a = 1; function nestedFunc() { @@ -929,7 +929,7 @@ s.lastNameCaps(); <p>闭包是 JavaScript 中最强大的抽象概念之一——但它也是最容易造成困惑的。它究竟是做什么的呢?</p> -<pre class="brush: js notranslate">function makeAdder(a) { +<pre class="brush: js">function makeAdder(a) { return function(b) { return a + b; } @@ -946,7 +946,7 @@ add20(7); // ? <p>这里发生的事情和前面介绍过的内嵌函数十分相似:一个函数被定义在了另外一个函数的内部,内部函数可以访问外部函数的变量。唯一的不同是,外部函数已经返回了,那么常识告诉我们局部变量“应该”不再存在。但是它们却仍然存在——否则 <code>adder</code> 函数将不能工作。也就是说,这里存在 <code>makeAdder</code> 的局部变量的两个不同的“副本”——一个是 <code>a</code> 等于 5,另一个是 <code>a</code> 等于 20。那些函数的运行结果就如下所示:</p> -<pre class="brush: js notranslate">add5(6); // 返回 11 +<pre class="brush: js">add5(6); // 返回 11 add20(7); // 返回 27 </pre> diff --git a/files/zh-cn/web/javascript/closures/index.html b/files/zh-cn/web/javascript/closures/index.html index 4b732a1a0d..29356fb61a 100644 --- a/files/zh-cn/web/javascript/closures/index.html +++ b/files/zh-cn/web/javascript/closures/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Closures <p>请看下面的代码:</p> <div style="width: auto; overflow: hidden;"> -<pre class="brush: js notranslate">function init() { +<pre class="brush: js">function init() { var name = "Mozilla"; // name 是一个被 init 创建的局部变量 function displayName() { // displayName() 是内部函数,一个闭包 alert(name); // 使用了父函数中声明的变量 @@ -37,7 +37,7 @@ init();</pre> <p>现在来考虑以下例子 :</p> -<pre class="brush: js notranslate">function makeFunc() { +<pre class="brush: js">function makeFunc() { var name = "Mozilla"; function displayName() { alert(name); @@ -56,7 +56,7 @@ myFunc();</pre> <p>下面是一个更有意思的示例 — 一个 <code>makeAdder</code> 函数:</p> -<pre class="brush: js notranslate">function makeAdder(x) { +<pre class="brush: js">function makeAdder(x) { return function(y) { return x + y; }; @@ -85,7 +85,7 @@ console.log(add10(2)); // 12 <p>假如,我们想在页面上添加一些可以调整字号的按钮。一种方法是以像素为单位指定 <code>body</code> 元素的 <code>font-size</code>,然后通过相对的 <code>em</code> 单位设置页面中其它元素(例如<code>header</code>)的字号:</p> -<pre class="brush: css notranslate">body { +<pre class="brush: css">body { font-family: Helvetica, Arial, sans-serif; font-size: 12px; } @@ -103,7 +103,7 @@ h2 { <p>以下是 JavaScript:</p> -<pre class="brush: js notranslate">function makeSizer(size) { +<pre class="brush: js">function makeSizer(size) { return function() { document.body.style.fontSize = size + 'px'; }; @@ -116,12 +116,12 @@ var size16 = makeSizer(16); <p><code>size12</code>,<code>size14</code> 和 <code>size16</code> 三个函数将分别把 <code>body</code> 文本调整为 12,14,16 像素。我们可以将它们分别添加到按钮的点击事件上。如下所示:</p> -<pre class="brush: js notranslate">document.getElementById('size-12').onclick = size12; +<pre class="brush: js">document.getElementById('size-12').onclick = size12; document.getElementById('size-14').onclick = size14; document.getElementById('size-16').onclick = size16; </pre> -<pre class="brush: html notranslate"><a href="#" id="size-12">12</a> +<pre class="brush: html"><a href="#" id="size-12">12</a> <a href="#" id="size-14">14</a> <a href="#" id="size-16">16</a> </pre> @@ -136,7 +136,7 @@ document.getElementById('size-16').onclick = size16; <p>下面的示例展现了如何使用闭包来定义公共函数,并令其可以访问私有函数和变量。这个方式也称为 <a class="external" href="http://www.google.com/search?q=javascript+module+pattern" title="http://www.google.com/search?q=javascript+module+pattern">模块模式(module pattern):</a></p> -<pre class="brush: js notranslate">var Counter = (function() { +<pre class="brush: js">var Counter = (function() { var privateCounter = 0; function changeBy(val) { privateCounter += val; @@ -172,7 +172,7 @@ console.log(Counter.value()); /* logs 1 */ <p>你应该注意到我们定义了一个匿名函数,用于创建一个计数器。我们立即执行了这个匿名函数,并将他的值赋给了变量<code>Counter</code>。我们可以把这个函数储存在另外一个变量<code>makeCounter</code>中,并用他来创建多个计数器。</p> </div> -<pre class="brush: js notranslate">var makeCounter = function() { +<pre class="brush: js">var makeCounter = function() { var privateCounter = 0; function changeBy(val) { privateCounter += val; @@ -213,13 +213,13 @@ console.log(Counter2.value()); /* logs 0 */ <p>在 ECMAScript 2015 引入 <a href="/en-US/docs/JavaScript/Reference/Statements/let" title="let"><code>let</code> 关键字</a> 之前,在循环中有一个常见的闭包创建问题。参考下面的示例:</p> -<pre class="brush: html notranslate"><p id="help">Helpful notes will appear here</p> +<pre class="brush: html"><p id="help">Helpful notes will appear here</p> <p>E-mail: <input type="text" id="email" name="email"></p> <p>Name: <input type="text" id="name" name="name"></p> <p>Age: <input type="text" id="age" name="age"></p> </pre> -<pre class="brush: js notranslate">function showHelp(help) { +<pre class="brush: js">function showHelp(help) { document.getElementById('help').innerHTML = help; } @@ -251,7 +251,7 @@ setupHelp(); <p>解决这个问题的一种方案是使用更多的闭包:特别是使用前面所述的函数工厂:</p> -<pre class="brush: js notranslate">function showHelp(help) { +<pre class="brush: js">function showHelp(help) { document.getElementById('help').innerHTML = help; } @@ -283,7 +283,7 @@ setupHelp(); <p>另一种方法使用了匿名闭包:</p> -<pre class="brush: js notranslate">function showHelp(help) { +<pre class="brush: js">function showHelp(help) { document.getElementById('help').innerHTML = help; } @@ -308,7 +308,7 @@ setupHelp();</pre> <p>如果不想使用过多的闭包,你可以用ES2015引入的let关键词:</p> -<pre class="brush: js notranslate">function showHelp(help) { +<pre class="brush: js">function showHelp(help) { document.getElementById('help').innerHTML = help; } @@ -333,7 +333,7 @@ setupHelp();</pre> <p>另一个可选方案是使用 <code>forEach()</code>来遍历<code>helpText</code>数组并给每一个<code><a href="/zh-CN/docs/Web/HTML/Element/p" title="The HTML <p> element represents a paragraph."><p></a></code>添加一个监听器,如下所示:</p> -<pre class="brush: js notranslate">function showHelp(help) { +<pre class="brush: js">function showHelp(help) { document.getElementById('help').innerHTML = help; } @@ -361,7 +361,7 @@ setupHelp();</pre> <p>考虑以下示例:</p> -<pre class="brush: js notranslate">function MyObject(name, message) { +<pre class="brush: js">function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); this.getName = function() { @@ -376,7 +376,7 @@ setupHelp();</pre> <p>在上面的代码中,我们并没有利用到闭包的好处,因此可以避免使用闭包。修改成如下:</p> -<pre class="brush: js notranslate">function MyObject(name, message) { +<pre class="brush: js">function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } @@ -393,7 +393,7 @@ MyObject.prototype = { <p>但我们不建议重新定义原型。可改成如下例子:</p> -<pre class="brush: js notranslate">function MyObject(name, message) { +<pre class="brush: js">function MyObject(name, message) { this.name = name.toString(); this.message = message.toString(); } diff --git a/files/zh-cn/web/javascript/data_structures/index.html b/files/zh-cn/web/javascript/data_structures/index.html index 43090ed41c..51597b130c 100644 --- a/files/zh-cn/web/javascript/data_structures/index.html +++ b/files/zh-cn/web/javascript/data_structures/index.html @@ -16,7 +16,7 @@ translation_of: Web/JavaScript/Data_structures <p>JavaScript 是一种<strong>弱类型</strong>或者说<strong>动态</strong>语言。这意味着你不用提前声明变量的类型,在程序运行过程中,类型会被自动确定。这也意味着你可以使用同一个变量保存不同类型的数据:</p> -<pre class="brush: js notranslate">var foo = 42; // foo is a Number now +<pre class="brush: js">var foo = 42; // foo is a Number now foo = "bar"; // foo is a String now foo = true; // foo is a Boolean now </pre> @@ -66,7 +66,7 @@ foo = true; // foo is a Boolean now <p>数字类型中只有一个整数有两种表示方法: 0 可表示为 -0 和 +0("0" 是 +0 的简写)。 在实践中,这也几乎没有影响。 例如 <code>+0 === -0</code> 为真。 但是,你可能要注意除以0的时候:</p> -<pre class="brush: js notranslate">42 / +0; // Infinity +<pre class="brush: js">42 / +0; // Infinity 42 / -0; // -Infinity </pre> @@ -78,7 +78,7 @@ foo = true; // foo is a Boolean now <p>通过使用常量{{jsxref("Number.MAX_SAFE_INTEGER")}},您可以获得可以用数字递增的最安全的值。通过引入 BigInt,您可以操作超过{{jsxref("Number.MAX_SAFE_INTEGER")}}的数字。您可以在下面的示例中观察到这一点,其中递增{{jsxref("Number.MAX_SAFE_INTEGER")}}会返回预期的结果:</p> -<pre class="notranslate"><code>> const x = 2n ** 53n; +<pre><code>> const x = 2n ** 53n; 9007199254740992n > const y = x + 1n; 9007199254740993n</code> diff --git a/files/zh-cn/web/javascript/enumerability_and_ownership_of_properties/index.html b/files/zh-cn/web/javascript/enumerability_and_ownership_of_properties/index.html index 47f75f244a..e7401b7cc1 100644 --- a/files/zh-cn/web/javascript/enumerability_and_ownership_of_properties/index.html +++ b/files/zh-cn/web/javascript/enumerability_and_ownership_of_properties/index.html @@ -145,7 +145,7 @@ translation_of: Web/JavaScript/Enumerability_and_ownership_of_properties <li>使用 <code>SimplePropertyRetriever.theGetMethodYouWant(obj).forEach(function (value, prop) {});</code> 时将发生迭代操作。 (或使用 <code>filter()</code>、<code>map()</code> 等方法)</li> </ul> -<pre class="brush: js notranslate">var SimplePropertyRetriever = { +<pre class="brush: js">var SimplePropertyRetriever = { getOwnEnumerables: function(obj) { return this._getPropertyNames(obj, true, false, this._enumerable); // Or could use for..in filtered with hasOwnProperty or just this: return Object.keys(obj); diff --git a/files/zh-cn/web/javascript/equality_comparisons_and_sameness/index.html b/files/zh-cn/web/javascript/equality_comparisons_and_sameness/index.html index 509f759b1d..5d8e0d7528 100644 --- a/files/zh-cn/web/javascript/equality_comparisons_and_sameness/index.html +++ b/files/zh-cn/web/javascript/equality_comparisons_and_sameness/index.html @@ -38,7 +38,7 @@ translation_of: Web/JavaScript/Equality_comparisons_and_sameness <p>全等操作符比较两个值是否相等,两个被比较的值在比较前都不进行隐式转换。如果两个被比较的值具有不同的类型,这两个值是不全等的。否则,如果两个被比较的值类型相同,值也相同,并且都不是 number 类型时,两个值全等。最后,如果两个值都是 number 类型,当两个都不是 NaN,并且数值相同,或是两个值分别为 +0 和 -0 时,两个值被认为是全等的。</p> -<pre class="brush: js notranslate">var num = 0; +<pre class="brush: js">var num = 0; var obj = new String("0"); var str = "0"; var b = false; @@ -145,7 +145,7 @@ console.log(obj === undefined); // false <p>一般而言,根据 ECMAScript 规范,所有的对象都与 <code>undefined </code>和 <code>null </code>不相等。但是大部分浏览器允许非常窄的一类对象(即,所有页面中的 <code>document.all </code>对象),在某些情况下,充当效仿 <code>undefined </code>的角色。相等操作符就是在这样的一个背景下。因此,<code>IsFalsy(A) </code>方法的值为 <code>true </code>,当且仅当 <code>A </code>效仿 <code>undefined</code>。在其他所有情况下,一个对象都不会等于 <code>undefined </code>或 <code>null</code>。</p> -<pre class="brush: js notranslate">var num = 0; +<pre class="brush: js">var num = 0; var obj = new String("0"); var str = "0"; var b = false; @@ -170,7 +170,7 @@ console.log(obj == undefined); <p>同值相等解决了最后一个用例:确定两个值是否在任何情况下功能上是相同的。(这个用例演示了<a href="http://zh.wikipedia.org/zh-cn/%E9%87%8C%E6%B0%8F%E6%9B%BF%E6%8D%A2%E5%8E%9F%E5%88%99">里氏替换原则</a>的实例。)当试图对不可变(immutable)属性修改时发生出现的情况:</p> -<pre class="brush: js notranslate">// 向 Nmuber 构造函数添加一个不可变的属性 NEGATIVE_ZERO +<pre class="brush: js">// 向 Nmuber 构造函数添加一个不可变的属性 NEGATIVE_ZERO Object.defineProperty(Number, "NEGATIVE_ZERO", { value: -0, writable: false, configurable: false, enumerable: false }); @@ -388,7 +388,7 @@ function attemptMutation(v) <dd> <p>显而易见,对<code>0一元负操作得到</code><code>-0</code>。但表达式的抽象化可能在你没有意识到得情况下导致-0延续传播。例如当考虑下例时:</p> - <pre class="brush:js language-js notranslate"><code class="language-js">let stoppingForce = obj.mass * -obj.velocity</code></pre> + <pre class="brush:js language-js"><code class="language-js">let stoppingForce = obj.mass * -obj.velocity</code></pre> <div class="line-number" style="top: 0px;"></div> diff --git a/files/zh-cn/web/javascript/eventloop/index.html b/files/zh-cn/web/javascript/eventloop/index.html index 42b31a8fde..f9fdf69207 100644 --- a/files/zh-cn/web/javascript/eventloop/index.html +++ b/files/zh-cn/web/javascript/eventloop/index.html @@ -27,7 +27,7 @@ translation_of: Web/JavaScript/EventLoop <p>函数调用形成了一个由若干帧组成的栈。</p> -<pre class="brush: js notranslate">function foo(b) { +<pre class="brush: js">function foo(b) { let a = 10; return a + b + 11; } @@ -57,7 +57,7 @@ console.log(bar(7)); // 返回 42</pre> <p>之所以称之为 <strong>事件循环</strong>,是因为它经常按照类似如下的方式来被实现:</p> -<pre class="brush: js notranslate">while (queue.waitForMessage()) { +<pre class="brush: js">while (queue.waitForMessage()) { queue.processNextMessage(); }</pre> @@ -77,7 +77,7 @@ console.log(bar(7)); // 返回 42</pre> <p>下面的例子演示了这个概念(<code>setTimeout</code> 并不会在计时器到期之后直接执行):</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">const s = new Date().getSeconds(); +<pre class="brush: js line-numbers language-js"><code class="language-js">const s = new Date().getSeconds(); setTimeout(function() { // 输出 "2",表示回调函数并没有在 500 毫秒之后立即执行 @@ -99,7 +99,7 @@ while(true) { <p>基本上,<code>setTimeout</code> 需要等待当前队列中所有的消息都处理完毕之后才能执行,即使已经超出了由第二参数所指定的时间。</p> -<pre class="brush: js notranslate">(function() { +<pre class="brush: js">(function() { console.log('这是开始'); diff --git a/files/zh-cn/web/javascript/guide/details_of_the_object_model/index.html b/files/zh-cn/web/javascript/guide/details_of_the_object_model/index.html index 5beb697684..36f626ed0e 100644 --- a/files/zh-cn/web/javascript/guide/details_of_the_object_model/index.html +++ b/files/zh-cn/web/javascript/guide/details_of_the_object_model/index.html @@ -121,7 +121,7 @@ translation_of: Web/JavaScript/Guide/Details_of_the_Object_Model <tbody> <tr> <td> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function Employee () { this.name = ""; this.dept = "general"; @@ -129,7 +129,7 @@ function Employee () { </pre> </td> <td> - <pre class="brush: java notranslate"> + <pre class="brush: java"> public class Employee { public String name = ""; public String dept = "general"; @@ -151,7 +151,7 @@ public class Employee { <tbody> <tr> <td> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function Manager() { Employee.call(this); this.reports = []; @@ -165,7 +165,7 @@ function WorkerBee() { WorkerBee.prototype = Object.create(Employee.prototype);</pre> </td> <td> - <pre class="brush: java notranslate"> + <pre class="brush: java"> public class Manager extends Employee { public Employee[] reports = new Employee[0]; } @@ -192,7 +192,7 @@ public class WorkerBee extends Employee { <tbody> <tr> <td> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function SalesPerson() { WorkerBee.call(this); this.dept = 'sales'; @@ -208,7 +208,7 @@ function Engineer() { Engineer.prototype <code>= Object.create(WorkerBee.prototype);</code></pre> </td> <td> - <pre class="brush: java notranslate"> + <pre class="brush: java"> <code>public class SalesPerson extends WorkerBee { public String dept = "sales"; public double quota = 100.0; @@ -240,7 +240,7 @@ public class Engineer extends WorkerBee { <h4 id="个别对象">个别对象</h4> -<pre class="brush: js notranslate">var jim = new Employee; // 如构造函数无须接受任何参数,圆括号可以省略。 +<pre class="brush: js">var jim = new Employee; // 如构造函数无须接受任何参数,圆括号可以省略。 // jim.name is '' // jim.dept is 'general' @@ -274,14 +274,14 @@ var jane = new Engineer; <p>假设您通过如下语句创建一个<code>mark</code>对象作为 <code>WorkerBee</code>的实例:</p> -<pre class="brush: js notranslate">var mark = new WorkerBee; +<pre class="brush: js">var mark = new WorkerBee; </pre> <p>当 JavaScript 执行 <code>new</code> 操作符时,它会先创建一个普通对象,并将这个普通对象中的 [[prototype]] 指向 <code>WorkerBee.prototype</code> ,然后再把这个普通对象设置为执行 <code>WorkerBee</code> 构造函数时 <code>this</code> 的值。该普通对象的 [[Prototype]] 决定其用于检索属性的原型链。当构造函数执行完成后,所有的属性都被设置完毕,JavaScript 返回之前创建的对象,通过赋值语句将它的引用赋值给变量 <code>mark</code>。</p> <p>这个过程不会显式的将 <code style="font-size: 14px;">mark</code>所继承的原型链中的属性作为本地属性存放在 <code>mark</code> 对象中。当访问属性时,JavaScript 将首先检查对象自身中是否存在该属性,如果有,则返回该属性的值。如果不存在,JavaScript会检查原型链(使用内置的 [[Prototype]] )。如果原型链中的某个对象包含该属性,则返回这个属性的值。如果遍历整条原型链都没有找到该属性,JavaScript 则认为对象中不存在该属性,返回一个 <code>undefined</code>。这样,<code>mark</code> 对象中将具有如下的属性和对应的值:</p> -<pre class="brush: js notranslate">mark.name = ""; +<pre class="brush: js">mark.name = ""; mark.dept = "general"; mark.projects = []; </pre> @@ -290,7 +290,7 @@ mark.projects = []; <p>由于这些构造器不支持为实例设置特定的值,所以这些属性值仅仅是创建自 <code>WorkerBee</code> 的所有对象所共享的默认值。当然这些属性的值是可以修改的,所以您可以为 <code>mark</code>指定特定的信息,如下所示:</p> -<pre class="brush: js notranslate">mark.name = "Doe, Mark"; +<pre class="brush: js">mark.name = "Doe, Mark"; mark.dept = "admin"; mark.projects = ["navigator"];</pre> @@ -298,14 +298,14 @@ mark.projects = ["navigator"];</pre> <p>在 JavaScript 中,您可以在运行时为任何对象添加属性,而不必受限于构造函数提供的属性。添加特定于某个对象的属性,只需要为该对象指定一个属性值,如下所示:</p> -<pre class="brush: js notranslate">mark.bonus = 3000; +<pre class="brush: js">mark.bonus = 3000; </pre> <p>这样 <code>mark</code> 对象就有了 <code>bonus</code> 属性,而其它 <code>WorkerBee</code> 则没有该属性。</p> <p>如果您向某个构造函数的原型对象中添加新的属性,那么该属性将添加到从这个原型中继承属性的所有对象的中。例如,可以通过如下的语句向所有雇员中添加 <code>specialty</code> 属性:</p> -<pre class="brush: js notranslate">Employee.prototype.specialty = "none"; +<pre class="brush: js">Employee.prototype.specialty = "none"; </pre> <p>只要 JavaScript 执行了该语句,则 <code>mark</code> 对象也将具有 <code>specialty</code> 属性,其值为 <code>"none"</code>。下图则表示了在 <code>Employee</code> 原型中添加该属性,然后在 <code>Engineer</code> 的原型中重载该属性的效果。</p> @@ -332,7 +332,7 @@ mark.projects = ["navigator"];</pre> <tbody> <tr> <td> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function Employee (name, dept) { this.name = name || ""; this.dept = dept || "general"; @@ -340,7 +340,7 @@ function Employee (name, dept) { </pre> </td> <td> - <pre class="brush: java notranslate"> + <pre class="brush: java"> public class Employee { public String name; public String dept; @@ -360,7 +360,7 @@ public class Employee { </tr> <tr> <td> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function WorkerBee (projs) { this.projects = projs || []; } @@ -368,7 +368,7 @@ WorkerBee.prototype = new Employee; </pre> </td> <td> - <pre class="brush: java notranslate"> + <pre class="brush: java"> public class WorkerBee extends Employee { public String[] projects; public WorkerBee () { @@ -384,7 +384,7 @@ public class WorkerBee extends Employee { </tr> <tr> <td> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function Engineer (mach) { this.dept = "engineering"; @@ -394,7 +394,7 @@ Engineer.prototype = new WorkerBee; </pre> </td> <td> - <pre class="brush: java notranslate"> + <pre class="brush: java"> public class Engineer extends WorkerBee { public String machine; public Engineer () { @@ -414,7 +414,7 @@ public class Engineer extends WorkerBee { <p>上面使用 JavaScript 定义过程使用了一种设置默认值的特殊惯用法:</p> -<pre class="brush: js notranslate">this.name = name || ""; +<pre class="brush: js">this.name = name || ""; </pre> <p>JavaScript 的逻辑或操作符(<code>||</code>)会对第一个参数进行判断。如果该参数值运算后结果为真,则操作符返回该值。否则,操作符返回第二个参数的值。因此,这行代码首先检查 <code>name</code> 是否是对<code>name</code> 属性有效的值。如果是,则设置其为 <code>this.name</code> 的值。否则,设置 <code>this.name</code> 的值为空的字符串。尽管这种用法乍看起来有些费解,为了简洁起见,本章将使用这种习惯用法。</p> @@ -425,12 +425,12 @@ public class Engineer extends WorkerBee { <p>使用这些定义,当创建对象的实例时,可以为本地定义的属性指定值。你可以使用以下语句创建一个新的<code>Engineer</code>:</p> -<pre class="brush: js notranslate">var jane = new Engineer("belau"); +<pre class="brush: js">var jane = new Engineer("belau"); </pre> <p>此时,<code>Jane</code> 的属性如下所示:</p> -<pre class="brush: js notranslate">jane.name == ""; +<pre class="brush: js">jane.name == ""; jane.dept == "engineering"; jane.projects == []; jane.machine == "belau" @@ -445,7 +445,7 @@ jane.machine == "belau" <p>我们来详细看一下这些定义。这是<code>Engineer</code>构造函数的新定义:</p> -<pre class="brush: js notranslate">function Engineer (name, projs, mach) { +<pre class="brush: js">function Engineer (name, projs, mach) { this.base = WorkerBee; this.base(name, "engineering", projs); this.machine = mach || ""; @@ -454,7 +454,7 @@ jane.machine == "belau" <p>假设您创建了一个新的 <code>Engineer</code> 对象,如下所示:</p> -<pre class="brush: js notranslate">var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); +<pre class="brush: js">var jane = new Engineer("Doe, Jane", ["navigator", "javascript"], "belau"); </pre> <p>JavaScript 会按以下步骤执行:</p> @@ -475,7 +475,7 @@ jane.machine == "belau" <p>你可以认为,在 <code>Engineer</code> 的构造器中调用了 <code>WorkerBee</code> 的构造器,也就为 <code>Engineer</code> 对象设置好了继承关系。事实并非如此。调用 <code>WorkerBee</code> 构造器确保了<code>Engineer</code> 对象以所有在构造器中所指定的属性被调用。但是,如果后续在 <code>Employee</code> 或者 <code>WorkerBee</code> 原型中添加了属性,那些属性不会被 <code>Engineer</code> 对象继承。例如,假设如下语句:</p> -<pre class="brush: js notranslate">function Engineer (name, projs, mach) { +<pre class="brush: js">function Engineer (name, projs, mach) { this.base = WorkerBee; this.base(name, "engineering", projs); this.machine = mach || ""; @@ -486,7 +486,7 @@ Employee.prototype.specialty = "none"; <p>对象 <code>jane</code> 不会继承 <code>specialty</code> 属性。您必须显式地设置原型才能确保动态的继承。如果修改成如下的语句:</p> -<pre class="brush: js notranslate">function Engineer (name, projs, mach) { +<pre class="brush: js">function Engineer (name, projs, mach) { this.base = WorkerBee; this.base(name, "engineering", projs); this.machine = mach || ""; @@ -504,7 +504,7 @@ Employee.prototype.specialty = "none"; <tbody> <tr> <td> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function Engineer (name, projs, mach) { this.base = WorkerBee; this.base(name, "engineering", projs); @@ -513,7 +513,7 @@ function Engineer (name, projs, mach) { </pre> </td> <td> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function Engineer (name, projs, mach) { WorkerBee.call(this, name, "engineering", projs); this.machine = mach || ""; @@ -543,7 +543,7 @@ function Engineer (name, projs, mach) { <p>以上步骤的结果依赖于你是如何定义的。最早的例子中有如下定义:</p> -<pre class="brush: js notranslate">function Employee () { +<pre class="brush: js">function Employee () { this.name = ""; this.dept = "general"; } @@ -556,19 +556,19 @@ WorkerBee.prototype = new Employee; <p>基于这些定义,假定通过如下的语句创建 <code>WorkerBee</code> 的实例 <code>amy</code>:</p> -<pre class="brush: js notranslate">var amy = new WorkerBee; +<pre class="brush: js">var amy = new WorkerBee; </pre> <p>则 <code>amy</code> 对象将具有一个本地属性 <code>projects</code>。<code>name</code>和 <code>dept</code> 则不是 <code>amy</code> 对象的本地属性,而是从 <code>amy</code> 对象的 <code>__proto__</code> 属性获得的。因此,<code>amy</code> 将具有如下的属性值:</p> -<pre class="brush: js notranslate">amy.name == ""; +<pre class="brush: js">amy.name == ""; amy.dept == "general"; amy.projects == []; </pre> <p>现在,假设修改了与 <code>Employee</code> 的相关联原型中的 <code>name</code> 属性的值:</p> -<pre class="brush: js notranslate">Employee.prototype.name = "Unknown" +<pre class="brush: js">Employee.prototype.name = "Unknown" </pre> <p>乍一看,你可能觉得新的值会传播给所有 <code>Employee</code> 的实例。然而,并非如此。</p> @@ -577,7 +577,7 @@ amy.projects == []; <p>如果想在运行时修改一个对象的属性值并且希望该值被所有该对象的后代所继承,您就不能在该对象的构造器函数中定义该属性。而应该将该属性添加到该对象所关联的原型中。例如,假设将前面的代码作如下修改:</p> -<pre class="brush: js notranslate">function Employee () { +<pre class="brush: js">function Employee () { this.dept = "general"; } Employee.prototype.name = ""; @@ -604,17 +604,17 @@ Employee.prototype.name = "Unknown"; <p>每个对象都有一个 <code>__proto__</code> 对象属性(除了 <code>Object);每个函数都有一个</code> <code>prototype</code> 对象属性。因此,通过“原型继承”,对象与其它对象之间形成关系。通过比较对象的 <code>__proto__</code> 属性和函数的 <code>prototype</code> 属性可以检测对象的继承关系。JavaScript 提供了便捷方法:<code>instanceof</code> 操作符可以用来将一个对象和一个函数做检测,如果对象继承自函数的原型,则该操作符返回真。例如:</p> -<pre class="brush: js notranslate">var f = new Foo(); +<pre class="brush: js">var f = new Foo(); var isTrue = (f instanceof Foo);</pre> <p>作为详细一点的例子,假定我们使用和在 <a href="#Inheriting_properties">Inheriting properties</a> 中相同的一组定义。创建 <code>Engineer</code> 对象如下:</p> -<pre class="brush: js notranslate">var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji"); +<pre class="brush: js">var chris = new Engineer("Pigman, Chris", ["jsd"], "fiji"); </pre> <p>对于该对象,以下所有语句均为真:</p> -<pre class="brush: js notranslate">chris.__proto__ == Engineer.prototype; +<pre class="brush: js">chris.__proto__ == Engineer.prototype; chris.__proto__.__proto__ == WorkerBee.prototype; chris.__proto__.__proto__.__proto__ == Employee.prototype; chris.__proto__.__proto__.__proto__.__proto__ == Object.prototype; @@ -623,7 +623,7 @@ chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null; <p>基于此,可以写出一个如下所示的 <code>instanceOf</code> 函数:</p> -<pre class="brush: js notranslate">function instanceOf(object, constructor) { +<pre class="brush: js">function instanceOf(object, constructor) { while (object != null) { if (object == constructor.prototype) return true; @@ -642,7 +642,7 @@ chris.__proto__.__proto__.__proto__.__proto__.__proto__ == null; <div></div> -<pre class="brush: js notranslate">instanceOf (chris, Engineer) +<pre class="brush: js">instanceOf (chris, Engineer) instanceOf (chris, WorkerBee) instanceOf (chris, Employee) instanceOf (chris, Object) @@ -650,13 +650,13 @@ instanceOf (chris, Object) <p>但如下表达式为假:</p> -<pre class="brush: js notranslate">instanceOf (chris, SalesPerson)</pre> +<pre class="brush: js">instanceOf (chris, SalesPerson)</pre> <h3 id="构造器中的全局信息">构造器中的全局信息</h3> <p>在创建构造器时,在构造器中设置全局信息要小心。例如,假设希望为每一个雇员分配一个唯一标识。可能会为 <code>Employee</code> 使用如下定义:</p> -<pre class="brush: js notranslate">var idCounter = 1; +<pre class="brush: js">var idCounter = 1; function Employee (name, dept) { this.name = name || ""; @@ -667,13 +667,13 @@ function Employee (name, dept) { <p>基于该定义,在创建新的 <code>Employee</code> 时,构造器为其分配了序列中的下一个标识符。然后递增全局的标识符计数器。因此,如果,如果随后的语句如下,则 <code>victoria.id</code> 为 1 而 <code>harry.id</code> 为 2:</p> -<pre class="brush: js notranslate">var victoria = new Employee("Pigbert, Victoria", "pubs") +<pre class="brush: js">var victoria = new Employee("Pigbert, Victoria", "pubs") var harry = new Employee("Tschopik, Harry", "sales") </pre> <p>乍一看似乎没问题。但是,无论什么目的,在每一次创建 <code>Employee</code> 对象时,<code>idCounter</code> 都将被递增一次。如果创建本章中所描述的整个 <code>Employee</code> 层级结构,每次设置原型的时候,<code>Employee</code> 构造器都将被调用一次。假设有如下代码:</p> -<pre class="brush: js notranslate">var idCounter = 1; +<pre class="brush: js">var idCounter = 1; function Employee (name, dept) { this.name = name || ""; @@ -700,7 +700,7 @@ var mac = new Engineer("Wood, Mac"); <p>依赖于应用程序,计数器额外的递增可能有问题,也可能没问题。如果确实需要准确的计数器,则以下构造器可以作为一个可行的方案:</p> -<pre class="brush: js notranslate">function Employee (name, dept) { +<pre class="brush: js">function Employee (name, dept) { this.name = name || ""; this.dept = dept || "general"; if (name) @@ -712,7 +712,7 @@ var mac = new Engineer("Wood, Mac"); <p>或者,您可以创建一个 Employee 的原型对象的副本以分配给 WorkerBee:</p> -<pre class="brush: js notranslate">WorkerBee.prototype = Object.create(Employee.prototype); +<pre class="brush: js">WorkerBee.prototype = Object.create(Employee.prototype); // instead of WorkerBee.prototype = new Employee</pre> <h3 id="没有多重继承">没有多重继承</h3> @@ -723,7 +723,7 @@ var mac = new Engineer("Wood, Mac"); <p>在 JavaScript 中,可以在构造器函数中调用多个其它的构造器函数。这一点造成了多重继承的假象。例如,考虑如下语句:</p> -<pre class="brush: js notranslate">function Hobbyist (hobby) { +<pre class="brush: js">function Hobbyist (hobby) { this.hobby = hobby || "scuba"; } @@ -741,7 +741,7 @@ var dennis = new Engineer("Doe, Dennis", ["collabra"], "hugo") <p>进一步假设使用本章前面所属的 <code>WorkerBee</code> 的定义。此时 <code>dennis</code> 对象具有如下属性:</p> -<pre class="brush: js notranslate">dennis.name == "Doe, Dennis" +<pre class="brush: js">dennis.name == "Doe, Dennis" dennis.dept == "engineering" dennis.projects == ["collabra"] dennis.machine == "hugo" @@ -750,7 +750,7 @@ dennis.hobby == "scuba" <p><code>dennis</code> 确实从 <code>Hobbyist</code> 构造器中获得了 <code>hobby</code> 属性。但是,假设添加了一个属性到 <code>Hobbyist</code> 构造器的原型:</p> -<pre class="brush: js notranslate">Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"] +<pre class="brush: js">Hobbyist.prototype.equipment = ["mask", "fins", "regulator", "bcd"] </pre> <p><code>dennis</code> 对象不会继承这个新属性。</p> diff --git a/files/zh-cn/web/javascript/guide/expressions_and_operators/index.html b/files/zh-cn/web/javascript/guide/expressions_and_operators/index.html index 1ea851d0f7..b90c70b5e0 100644 --- a/files/zh-cn/web/javascript/guide/expressions_and_operators/index.html +++ b/files/zh-cn/web/javascript/guide/expressions_and_operators/index.html @@ -33,18 +33,18 @@ translation_of: Web/JavaScript/Guide/Expressions_and_Operators <p>JavaScript 拥有二元和一元运算符, 和一个特殊的三元运算符(条件运算符)。一个二元运算符需要两个操作数,分别在运算符的前面和后面:</p> -<pre class="notranslate"><em>操作数1 运算符 操作数2</em> +<pre><em>操作数1 运算符 操作数2</em> </pre> <p>例如, <code>3+4</code> 或 <code>x*y</code>。</p> <p>一个一元运算符需要一个操作数,在运算符前面或后面:</p> -<pre class="notranslate"><em>运算符 操作数</em></pre> +<pre><em>运算符 操作数</em></pre> <p>或</p> -<pre class="notranslate"><em>操作数 运算符</em></pre> +<pre><em>操作数 运算符</em></pre> <p>例如, <code>x++</code> 或 <code>++x</code>。</p> @@ -136,7 +136,7 @@ translation_of: Web/JavaScript/Guide/Expressions_and_Operators <p>对于更复杂的赋值,<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">解构赋值</a>语法是一个能从数组或对象对应的数组结构或对象字面量里提取数据的 Javascript 表达式。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var foo = ["one", "two", "three"]; +<pre class="brush: js line-numbers language-js"><code class="language-js">var foo = ["one", "two", "three"]; // 不使用解构 var one = foo[0]; @@ -150,7 +150,7 @@ var [one, two, three] = foo;</code></pre> <p><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/Comparison_Operators">比较运算符</a>比较它的操作数并返回一个基于表达式是否为真的逻辑值。操作数可以是数字,字符串,逻辑,对象值。字符串比较是基于标准的字典顺序,使用Unicode值。在多数情况下,如果两个操作数不是相同的类型, JavaScript 会尝试转换它们为恰当的类型来比较。这种行为通常发生在数字作为操作数的比较。类型转换的例外是使用 <code>===</code> 和 <code>!==</code> 操作符,它们会执行严格的相等和不相等比较。这些运算符不会在检查相等之前转换操作数的类型。下面的表格描述了该示例代码中的各比较运算符</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var var1 = 3; +<pre class="brush: js line-numbers language-js"><code class="language-js">var var1 = 3; var var2 = 4;</code></pre> <table class="standard-table"> @@ -224,7 +224,7 @@ var var2 = 4;</code></pre> <p>算术运算符使用数值(字面量或者变量)作为操作数并返回一个数值.标准的算术运算符就是加减乘除(+ - * /)。当操作数是浮点数时,这些运算符表现得跟它们在大多数编程语言中一样(特殊要注意的是,除零会产生{{jsxref("Infinity")}})。例如:</p> -<pre class="brush: js notranslate">1 / 2; // 0.5 +<pre class="brush: js">1 / 2; // 0.5 1 / 2 == 1.0 / 2.0; // true </pre> @@ -378,7 +378,7 @@ var var2 = 4;</code></pre> <dl> <dt> - <pre class="notranslate"><code>Before: 11100110111110100000000000000110000000000001 + <pre><code>Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001</code></pre> </dt> </dl> @@ -507,7 +507,7 @@ After: 10100000000000000110000000000001</code></pre> <p>下面是&&(逻辑"与")操作符的示例。</p> -<pre class="brush: js notranslate">var a1 = true && true; // t && t returns true +<pre class="brush: js">var a1 = true && true; // t && t returns true var a2 = true && false; // t && f returns false var a3 = false && true; // f && t returns false var a4 = false && (3 == 4); // f && f returns false @@ -518,7 +518,7 @@ var a7 = "Cat" && false; // t && f returns false <p>下面是||(逻辑"或")操作符的示例。</p> -<pre class="brush: js notranslate">var o1 = true || true; // t || t returns true +<pre class="brush: js">var o1 = true || true; // t || t returns true var o2 = false || true; // f || t returns true var o3 = true || false; // t || f returns true var o4 = false || (3 == 4); // f || f returns false @@ -529,7 +529,7 @@ var o7 = "Cat" || false; // t || f returns Cat <p>下面是!(逻辑"非")操作符的示例。</p> -<pre class="brush: js notranslate">var n1 = !true; // !t returns false +<pre class="brush: js">var n1 = !true; // !t returns false var n2 = !false; // !f returns true var n3 = !"Cat"; // !t returns false </pre> @@ -551,11 +551,11 @@ var n3 = !"Cat"; // !t returns false <p>例如,</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">console.log("my " + "string"); // console logs the string "my string".</code></pre> +<pre class="brush: js line-numbers language-js"><code class="language-js">console.log("my " + "string"); // console logs the string "my string".</code></pre> <p>简写操作符 <code>+=</code> 也可以用来拼接字符串,例如:</p> -<pre class="brush: js notranslate"><code>var myString = "alpha";</code> +<pre class="brush: js"><code>var myString = "alpha";</code> <code>myString += "bet"; // 返回 "alphabet" </code> </pre> @@ -564,14 +564,14 @@ var n3 = !"Cat"; // !t returns false <p><a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">条件运算符</a>是JavaScript中唯一需要三个操作数的运算符。运算的结果根据给定条件在两个值中取其一。语法为:</p> -<pre class="notranslate"><em>条件 </em>?<em> 值1 </em>:<em> 值2</em> +<pre><em>条件 </em>?<em> 值1 </em>:<em> 值2</em> </pre> <p>如果<code>条件</code>为真,则结果取<code>值1</code>。否则为<code>值2</code>。你能够在任何允许使用标准运算符的地方使用条件运算符。</p> <p>例如,</p> -<pre class="brush: js notranslate">var status = (age >= 18) ? "adult" : "minor"; +<pre class="brush: js">var status = (age >= 18) ? "adult" : "minor"; </pre> <p>当 <code>age</code> 大于等于18的时候,将“adult”赋值给<code> status</code>;否则将“minor”赋值给 <code>status</code>。</p> @@ -582,7 +582,7 @@ var n3 = !"Cat"; // !t returns false <p>例如,假如 <code>a</code> 是一个二维数组,每个维度各有10个元素,以下代码利用逗号操作符来同时改变两个变量的值。这段代码的功能是打印出该二维数组的对角线元素的值:</p> -<pre class="brush: js notranslate">var x = [0,1,2,3,4,5,6,7,8,9] +<pre class="brush: js">var x = [0,1,2,3,4,5,6,7,8,9] var a = [x, x, x, x, x]; for (var i = 0, j = 9; i <= j; i++, j--) @@ -596,7 +596,7 @@ for (var i = 0, j = 9; i <= j; i++, j--) <p><code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete</a></code>操作符,删除一个对象的属性或者一个数组中某一个键值。语法如下:</p> -<pre class="brush: js notranslate">delete objectName.property; +<pre class="brush: js">delete objectName.property; delete objectName[index]; delete property; // legal only within a with statement </pre> @@ -609,7 +609,7 @@ delete property; // legal only within a with statement <p>如果 <code>delete</code> 操作成功,属性或者元素会变成 <code>undefined</code>。如果 <code>delete</code>可行会返回<code>true</code>,如果不成功返回<code>false</code>。</p> -<pre class="brush: js notranslate">x = 42; +<pre class="brush: js">x = 42; var y = 43; myobj = new Number(); myobj.h = 4; // create property h @@ -626,7 +626,7 @@ delete myobj; // returns true (can delete if declared implicitly) <p><code>delete</code> 删除数组中的一个元素,这个元素就不在数组中了。例如,<code>trees[3]</code>被删除,<code>trees[3]</code> 仍然可寻址并返回<code>undefined</code>。</p> -<pre class="brush: js notranslate">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +<pre class="brush: js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); delete trees[3]; if (3 in trees) { // 不会被执行 @@ -635,7 +635,7 @@ if (3 in trees) { <p>如果想让数组中存在一个元素但是是<code>undefined</code>值,使用<code>undefined</code>关键字而不是<code>delete</code>操作. 如下: <code>trees[3]分配一个undefined</code>,但是这个数组元素仍然存在:</p> -<pre class="brush: js notranslate">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +<pre class="brush: js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); trees[3] = undefined; if (3 in trees) { // this gets executed(会被执行) @@ -646,7 +646,7 @@ if (3 in trees) { <p><a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof">typeof操作符</a> 可通过下面2种方式使用:</p> -<pre class="brush: js notranslate">typeof operand +<pre class="brush: js">typeof operand typeof (operand) </pre> @@ -654,7 +654,7 @@ typeof (operand) <p>假设你定义了如下的变量:</p> -<pre class="brush: js notranslate">var myFun = new Function("5 + 2"); +<pre class="brush: js">var myFun = new Function("5 + 2"); var shape = "round"; var size = 1; var today = new Date(); @@ -662,7 +662,7 @@ var today = new Date(); <p>typeof 操作符将会返回如下的结果:</p> -<pre class="brush: js notranslate">typeof myFun; // returns "function" +<pre class="brush: js">typeof myFun; // returns "function" typeof shape; // returns "string" typeof size; // returns "number" typeof today; // returns "object" @@ -671,26 +671,26 @@ typeof dontExist; // returns "undefined" <p>对于关键词 <code>true</code> 和 <code>null</code>, <code>typeof</code> 操作符将会返回如下结果:</p> -<pre class="brush: js notranslate">typeof true; // returns "boolean" +<pre class="brush: js">typeof true; // returns "boolean" typeof null; // returns "object" </pre> <p>对于一个数值或字符串<code></code>, <code>typeof</code> 操作符将会返回如下结果:</p> -<pre class="brush: js notranslate">typeof 62; // returns "number" +<pre class="brush: js">typeof 62; // returns "number" typeof 'Hello world'; // returns "string" </pre> <p>对于属性值,typeof 操作符将会返回属性所包含值的类型:</p> -<pre class="brush: js notranslate">typeof document.lastModified; // returns "string" +<pre class="brush: js">typeof document.lastModified; // returns "string" typeof window.length; // returns "number" typeof Math.LN2; // returns "number" </pre> <p>对于方法和函数,typeof 操作符将会返回如下结果:</p> -<pre class="brush: js notranslate">typeof blur; // returns "function" +<pre class="brush: js">typeof blur; // returns "function" typeof eval; // returns "function" typeof parseInt; // returns "function" typeof shape.split; // returns "function" @@ -698,7 +698,7 @@ typeof shape.split; // returns "function" <p>对于预定义的对象,typeof 操作符将会返回如下结果:</p> -<pre class="brush: js notranslate">typeof Date; // returns "function" +<pre class="brush: js">typeof Date; // returns "function" typeof Function; // returns "function" typeof Math; // returns "object" typeof Option; // returns "function" @@ -709,7 +709,7 @@ typeof String; // returns "function" <p>void 运算符运用方法如下:</p> -<pre class="brush: js notranslate">void (expression) +<pre class="brush: js">void (expression) void expression </pre> @@ -719,11 +719,11 @@ void expression <p>如下创建了一个超链接文本,当用户单击该文本时,不会有任何效果。</p> -<pre class="brush: html line-numbers language-html notranslate"><code class="language-html"><a href="javascript:void(0)">Click here to do nothing</a></code></pre> +<pre class="brush: html line-numbers language-html"><code class="language-html"><a href="javascript:void(0)">Click here to do nothing</a></code></pre> <p>下面的代码创建了一个超链接,当用户单击它时,提交一个表单。</p> -<pre class="brush: html line-numbers language-html notranslate"><code class="language-html"><a href="javascript:void(document.form.submit())"> +<pre class="brush: html line-numbers language-html"><code class="language-html"><a href="javascript:void(document.form.submit())"> Click here to submit</a></code></pre> <h3 id="关系操作符">关系操作符</h3> @@ -734,14 +734,14 @@ Click here to submit</a></code></pre> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in"><code>in</code>操作符</a>,如果所指定的<strong>属性</strong>确实存在于所指定的对象中,则会返回<code>true</code>,语法如下:</p> -<pre class="brush: js notranslate">propNameOrNumber in objectName +<pre class="brush: js">propNameOrNumber in objectName </pre> <p>在这里 <code>propNameOrNumber</code>可以是一个代表着属性名的字符串或者是一个代表着数组索引的数值表达式,而<code>objectName</code>则是一个对象名。</p> <p>下面的例子是 <code>in</code> 操作的常见用法。</p> -<pre class="brush: js notranslate">// Arrays +<pre class="brush: js">// Arrays var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); 0 in trees; // returns true 3 in trees; // returns true @@ -765,7 +765,7 @@ var mycar = {make: "Honda", model: "Accord", year: 1998}; <p>如果所判别的对象确实是所指定的类型,则返回<code>true</code>。其语法如下:</p> -<pre class="brush: js notranslate">objectName instanceof objectType +<pre class="brush: js">objectName instanceof objectType </pre> <p><code>objectName</code> 是需要做判别的对象的名称,而<code>objectType</code>是假定的对象的类型, 例如{{jsxref("Date")}}或 {{jsxref("Array")}}.</p> @@ -774,7 +774,7 @@ var mycar = {make: "Honda", model: "Accord", year: 1998}; <p>例如, 下面的代码使用<code>instanceof</code>去判断 <code>theDay</code>是否是一个 <code>Date</code> 对象. <code>因为theDay</code>是一个<code>Date</code>对象, <code>所以if</code>中的代码会执行.</p> -<pre class="brush: js notranslate">var theDay = new Date(1995, 12, 17); +<pre class="brush: js">var theDay = new Date(1995, 12, 17); if (theDay instanceof Date) { // statements to execute } @@ -891,13 +891,13 @@ if (theDay instanceof Date) { <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this"><code>this</code></a>关键字被用于指代当前的对象,通常,<code>this</code>指代的是方法中正在被调用的对象。用法如下:</p> -<pre class="brush: js notranslate">this["propertyName"] +<pre class="brush: js">this["propertyName"] this.propertyName </pre> <p>假设一个用于验证对象<code>value</code>属性的<code>validate</code>函数,传参有对象,最高值和最低值。</p> -<pre class="brush: js notranslate">function validate(obj, lowval, hival){ +<pre class="brush: js">function validate(obj, lowval, hival){ if ((obj.value < lowval) || (obj.value > hival)) console.log("Invalid Value!"); } @@ -905,7 +905,7 @@ this.propertyName <p>你可以在任何表单元素的<code>onchange</code>事件处理中调用<code>validat</code>函数,用<code>this</code>来指代当前的表单元素,用例如下:</p> -<pre class="brush: html notranslate"><p>Enter a number between 18 and 99:</p> +<pre class="brush: html"><p>Enter a number between 18 and 99:</p> <input type="text" name="age" size=3 onChange="validate(this, 18, 99);"> </pre> @@ -913,7 +913,7 @@ this.propertyName <p>分组操作符()控制了表达式中计算的优先级. 举例来说, 你可以改变先乘除后加减的顺序,转而先计算加法。</p> -<pre class="brush:js line-numbers language-js notranslate"><code class="language-js">var a = 1; +<pre class="brush:js line-numbers language-js"><code class="language-js">var a = 1; var b = 2; var c = 3; @@ -941,7 +941,7 @@ a * c + b * c // 9</code></pre> <p>Comprehensions特性被许多编程语言所采用,该特性能够使你快速地通过一个已有的数组来创建出一个新的数组,比如:</p> -<pre class="brush:js line-numbers language-js notranslate"><code class="language-js">[for (i of [ 1, 2, 3 ]) i*i ]; +<pre class="brush:js line-numbers language-js"><code class="language-js">[for (i of [ 1, 2, 3 ]) i*i ]; // [ 1, 4, 9 ] var abc = [ "A", "B", "C" ]; @@ -956,14 +956,14 @@ var abc = [ "A", "B", "C" ]; <p>你可以使用<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new"><code>new</code> operator</a> 创建一个自定义类型或者是<code>预置类型</code>的对象实例。用法如下:</p> -<pre class="brush: js notranslate">var objectName = new objectType([param1, param2, ..., paramN]); +<pre class="brush: js">var objectName = new objectType([param1, param2, ..., paramN]); </pre> <p>super</p> <p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super">super </a>关键字可以用来调用一个对象父类的函数,它在用来调用一个<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">类</a>的父类的构造函数时非常有用,比如:</p> -<pre class="notranslate">super([arguments]); // calls the parent constructor. super.functionOnParent([arguments]);</pre> +<pre>super([arguments]); // calls the parent constructor. super.functionOnParent([arguments]);</pre> <h4 id="扩展语句">扩展语句</h4> @@ -971,12 +971,12 @@ var abc = [ "A", "B", "C" ]; <p><strong>例如:</strong>现在你有一个数组,你想创建一个新数组,并将刚才那个作为它的一部分,用array的字面语法是不够的,你不得不写一些代码实现它,比如用些<code>push</code>, <code>splice</code>, <code>concat等等。但是用</code>spread syntax就没问题了:</p> -<pre class="notranslate"><code>var parts = ['shoulder', 'knees']; +<pre><code>var parts = ['shoulder', 'knees']; var lyrics = ['head', ...parts, 'and', 'toes'];</code></pre> <p>类似的,扩展语句也可以用在函数调用的时候:</p> -<pre class="notranslate"><code>function f(x, y, z) { } +<pre><code>function f(x, y, z) { } var args = [0, 1, 2]; f(...args);</code></pre> diff --git a/files/zh-cn/web/javascript/guide/functions/index.html b/files/zh-cn/web/javascript/guide/functions/index.html index 3d43d61305..54e0bffa4b 100644 --- a/files/zh-cn/web/javascript/guide/functions/index.html +++ b/files/zh-cn/web/javascript/guide/functions/index.html @@ -30,21 +30,21 @@ translation_of: Web/JavaScript/Guide/Functions <p>例如,以下的代码定义了一个简单的<code>square</code>函数:</p> -<pre class="brush: js notranslate">function square(number) { +<pre class="brush: js">function square(number) { return number * number; } </pre> <p>函数<code>square</code>使用了一个参数,叫作<code>number</code>。这个函数只有一个语句,它说明该函数将函数的参数(即<code>number</code>)自乘后返回。函数的<a href="/en-US/docs/JavaScript/Reference/Statements/return" title="return"><code>return</code></a>语句确定了函数的返回值:</p> -<pre class="brush: js notranslate">return number * number; +<pre class="brush: js">return number * number; </pre> <p>原始参数(比如一个具体的数字)被作为<strong>值</strong>传递给函数;值被传递给函数,如果被调用函数改变了这个参数的值,这样的改变不会影响到全局或调用函数。</p> <p>如果你传递一个对象(即一个非原始值,例如{{jsxref("Array")}}或用户自定义的对象)作为参数,而函数改变了这个对象的属性,这样的改变对函数外部是可见的,如下面的例子所示:</p> -<pre class="brush: js notranslate">function myFunc(theObject) { +<pre class="brush: js">function myFunc(theObject) { theObject.make = "Toyota"; } @@ -62,19 +62,19 @@ y = mycar.make; // y获取的值为 "Toyota" <p>虽然上面的函数声明在语法上是一个语句,但函数也可以由函数表达式创建。这样的函数可以是<strong>匿名</strong>的;它不必有一个名称。例如,函数<code>square</code>也可这样来定义:</p> -<pre class="brush: js notranslate"><code>const square = function(number) { return number * number; }; +<pre class="brush: js"><code>const square = function(number) { return number * number; }; var x = square(4); // x gets the value 16</code></pre> <p>然而,函数表达式也可以提供函数名,并且可以用于在函数内部代指其本身,或者在调试器堆栈跟踪中识别该函数:</p> -<pre class="brush: js notranslate">const factorial = function fac(n) {return n<2 ? 1 : n*fac(n-1)}; +<pre class="brush: js">const factorial = function fac(n) {return n<2 ? 1 : n*fac(n-1)}; console.log(factorial(3)); </pre> <p>当将函数作为参数传递给另一个函数时,函数表达式很方便。下面的例子演示了一个叫<code>map</code>的函数如何被定义,而后使用一个表达式函数作为其第一个参数进行调用:</p> -<pre class="brush: js notranslate">function map(f,a) { +<pre class="brush: js">function map(f,a) { let result = []; // 创建一个数组 let i; // 声明一个值,用来循环 for (i = 0; i != a.length; i++) @@ -85,7 +85,7 @@ console.log(factorial(3)); <p>下面的代码:</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">function map(f, a) { +<pre class="brush: js line-numbers language-js"><code class="language-js">function map(f, a) { let result = []; // 创建一个数组 let i; // 声明一个值,用来循环 for (i = 0; i != a.length; i++) @@ -103,7 +103,7 @@ console.log(cube);</code></pre> <p>在 JavaScript 中,可以根据条件来定义一个函数。比如下面的代码,当<code>num</code> 等于 0 的时候才会定义 <code>myFunc</code> :</p> -<pre class="brush: js notranslate">var myFunc; +<pre class="brush: js">var myFunc; if (num == 0){ myFunc = function(theObject) { theObject.make = "Toyota" @@ -118,14 +118,14 @@ if (num == 0){ <p>定义一个函数并不会自动的执行它。定义了函数仅仅是赋予函数以名称并明确函数被调用时该做些什么。<strong>调用</strong>函数才会以给定的参数真正执行这些动作。例如,一旦你定义了函数<code>square</code>,你可以如下这样调用它:</p> -<pre class="brush: js notranslate">square(5); +<pre class="brush: js">square(5); </pre> <p>上述语句通过提供参数 5 来调用函数。函数执行完它的语句会返回值25。</p> <p>函数一定要处于调用它们的域中,但是函数的声明可以被提升(出现在调用语句之后),如下例:</p> -<pre class="brush: js notranslate">console.log(square(5)); +<pre class="brush: js">console.log(square(5)); /* ... */ function square(n) { return n*n } </pre> @@ -136,7 +136,7 @@ function square(n) { return n*n } <p><strong>提示:</strong>注意只有使用如上的语法形式(即 <code>function funcName(){}</code>)才可以。而下面的代码是无效的。就是说,函数提升仅适用于函数声明,而不适用于函数表达式。</p> </div> -<pre class="brush: js example-bad line-numbers language-js notranslate"><code class="language-js">console.log(square); // square is hoisted with an initial value undefined. +<pre class="brush: js example-bad line-numbers language-js"><code class="language-js">console.log(square); // square is hoisted with an initial value undefined. console.log(square(5)); // Uncaught TypeError: square is not a function const square = function (n) { return n * n; @@ -146,7 +146,7 @@ const square = function (n) { <p>函数可以被递归,就是说函数可以调用其本身。例如,下面这个函数就是用递归计算阶乘:</p> -<pre class="brush: js notranslate">function factorial(n){ +<pre class="brush: js">function factorial(n){ if ((n == 0) || (n == 1)) return 1; else @@ -156,7 +156,7 @@ const square = function (n) { <p>你可以计算1-5的阶乘如下:</p> -<pre class="brush: js notranslate">var a, b, c, d, e; +<pre class="brush: js">var a, b, c, d, e; a = factorial(1); // 1赋值给a b = factorial(2); // 2赋值给b @@ -171,7 +171,7 @@ e = factorial(5); // 120赋值给e <p>在函数内定义的变量不能在函数之外的任何地方访问,因为变量仅仅在该函数的域的内部有定义。相对应的,一个函数可以访问定义在其范围内的任何变量和函数。换言之,定义在全局域中的函数可以访问所有定义在全局域中的变量。在另一个函数中定义的函数也可以访问在其父函数中定义的所有变量和父函数有权访问的任何其他变量。</p> -<pre class="brush: js notranslate">// 下面的变量定义在全局作用域(global scope)中 +<pre class="brush: js">// 下面的变量定义在全局作用域(global scope)中 var num1 = 20, num2 = 3, name = "Chamahk"; @@ -212,7 +212,7 @@ getScore(); // 返回 "Chamahk scored 5" <p>例如,思考一下如下的函数定义:</p> -<pre class="brush: js notranslate">var foo = function bar() { +<pre class="brush: js">var foo = function bar() { // statements go here }; </pre> @@ -227,7 +227,7 @@ getScore(); // 返回 "Chamahk scored 5" <p>调用自身的函数我们称之为<em>递归函数</em>。在某种意义上说,递归近似于循环。两者都重复执行相同的代码,并且两者都需要一个终止条件(避免无限循环或者无限递归)。例如以下的循环:</p> -<pre class="brush: js notranslate">var x = 0; +<pre class="brush: js">var x = 0; while (x < 10) { // "x < 10" 是循环条件 // do stuff x++; @@ -236,7 +236,7 @@ while (x < 10) { // "x < 10" 是循环条件 <p>可以被转化成一个递归函数和对其的调用:</p> -<pre class="brush: js notranslate">function loop(x) { +<pre class="brush: js">function loop(x) { if (x >= 10) // "x >= 10" 是退出条件(等同于 "!(x < 10)") return; // 做些什么 @@ -247,7 +247,7 @@ loop(0); <p>不过,有些算法并不能简单的用迭代来实现。例如,获取树结构中所有的节点时,使用递归实现要容易得多:</p> -<pre class="brush: js notranslate">function walkTree(node) { +<pre class="brush: js">function walkTree(node) { if (node == null) // return; // do something with node @@ -263,7 +263,7 @@ loop(0); <p>这种类似堆栈的行为可以在下例中看到:</p> -<pre class="brush: js notranslate">function foo(i) { +<pre class="brush: js">function foo(i) { if (i < 0) return; console.log('begin:' + i); @@ -298,7 +298,7 @@ foo(3); <p>下面的例子展示了嵌套函数:</p> -<pre class="brush: js notranslate">function addSquares(a, b) { +<pre class="brush: js">function addSquares(a, b) { function square(x) { return x * x; } @@ -310,7 +310,7 @@ c = addSquares(4, 5); // returns 41</pre> <p>由于内部函数形成了闭包,因此你可以调用外部函数并为外部函数和内部函数指定参数:</p> -<pre class="brush: js notranslate">function outside(x) { +<pre class="brush: js">function outside(x) { function inside(y) { return x + y; } @@ -333,7 +333,7 @@ result1 = outside(3)(5); // returns 8</pre> <p>思考一下下面的例子:</p> -<pre class="brush: js notranslate">function A(x) { +<pre class="brush: js">function A(x) { function B(y) { function C(z) { console.log(x + y + z); @@ -360,7 +360,7 @@ A(1); // logs 6 (1 + 2 + 3)</pre> <p>看以下的例子:</p> -<pre class="brush: js notranslate">function outside() { +<pre class="brush: js">function outside() { var x = 5; function inside(x) { return x * 2; @@ -380,7 +380,7 @@ outside()(10); // returns 20 instead of 10</pre> <p>此外,由于内部函数可以访问外部函数的作用域,因此当内部函数生存周期大于外部函数时,外部函数中定义的变量和函数的生存周期将比内部函数执行时间长。当内部函数以某一种方式被任何一个外部函数作用域访问时,一个闭包就产生了。</p> -<pre class="brush: js notranslate">var pet = function(name) { //外部函数定义了一个变量"name" +<pre class="brush: js">var pet = function(name) { //外部函数定义了一个变量"name" var getName = function() { //内部函数可以访问 外部函数定义的"name" return name; @@ -395,7 +395,7 @@ myPet(); // 返回结果 "Vivie" <p>实际上可能会比上面的代码复杂的多。在下面这种情形中,返回了一个包含可以操作外部函数的内部变量方法的对象。</p> -<pre class="brush: js notranslate">var createPet = function(name) { +<pre class="brush: js">var createPet = function(name) { var sex; return { @@ -431,7 +431,7 @@ pet.getName(); // Oliver <p>在上面的代码中,外部函数的<code>name</code>变量对内嵌函数来说是可取得的,而除了通过内嵌函数本身,没有其它任何方法可以取得内嵌的变量。内嵌函数的内嵌变量就像内嵌函数的保险柜。它们会为内嵌函数保留“稳定”——而又安全——的数据参与运行。而这些内嵌函数甚至不会被分配给一个变量,或者不必一定要有名字。</p> -<pre class="brush: js notranslate">var getCode = (function(){ +<pre class="brush: js">var getCode = (function(){ var secureCode = "0]Eal(eh&2"; // A code we do not want outsiders to be able to modify... return function () { @@ -445,7 +445,7 @@ getCode(); // Returns the secret code <div class="blockIndicator note"> <p>尽管有上述优点,使用闭包时仍然要小心避免一些陷阱。如果一个闭包的函数定义了一个和外部函数的某个变量名称相同的变量,那么这个闭包将无法引用外部函数的这个变量。</p> -<pre class="brush: js notranslate">var createPet = function(name) { // Outer function defines a variable called "name" +<pre class="brush: js">var createPet = function(name) { // Outer function defines a variable called "name" return { setName: function(name) { // Enclosed function also defines a variable called "name" name = name; // ??? How do we access the "name" defined by the outer function ??? @@ -459,7 +459,7 @@ getCode(); // Returns the secret code <p>函数的实际参数会被保存在一个类似数组的arguments对象中。在函数内,你可以按如下方式找出传入的参数:</p> -<pre class="brush: js notranslate">arguments[i] +<pre class="brush: js">arguments[i] </pre> <p>其中<code>i</code>是参数的序数编号(译注:数组索引),以0开始。所以第一个传来的参数会是<code>arguments[0]</code>。参数的数量由<code>arguments.length</code>表示。</p> @@ -468,7 +468,7 @@ getCode(); // Returns the secret code <p>例如,设想有一个用来连接字符串的函数。唯一事先确定的参数是在连接后的字符串中用来分隔各个连接部分的字符(译注:比如例子里的分号“;”)。该函数定义如下:</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">function myConcat(separator) { +<pre class="brush: js line-numbers language-js"><code class="language-js">function myConcat(separator) { var result = ''; // 把值初始化成一个字符串,这样就可以用来保存字符串了!! var i; // iterate through arguments @@ -480,7 +480,7 @@ getCode(); // Returns the secret code <p>你可以给这个函数传递任意数量的参数,它会将各个参数连接成一个字符串“列表”:</p> -<pre class="brush: js notranslate">// returns "red, orange, blue, " +<pre class="brush: js">// returns "red, orange, blue, " myConcat(", ", "red", "orange", "blue"); // returns "elephant; giraffe; lion; cheetah; " @@ -504,7 +504,7 @@ myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley"); <p>在过去,用于设定默认参数的一般策略是在函数的主体中测试参数值是否为<code>undefined</code>,如果是则赋予这个参数一个默认值。如果在下面的例子中,调用函数时没有实参传递给<code>b</code>,那么它的值就是<code>undefined</code>,于是计算<code>a*b</code>得到、函数返回的是 <code>NaN</code>。但是,在下面的例子中,这个已经被第二行获取处理:</p> -<pre class="brush: js notranslate">function multiply(a, b) { +<pre class="brush: js">function multiply(a, b) { b = (typeof b !== 'undefined') ? b : 1; return a*b; @@ -515,7 +515,7 @@ multiply(5); // 5 <p>使用默认参数,在函数体的检查就不再需要了。现在,你可以在函数头简单地把1设定为<code>b</code>的默认值:</p> -<pre class="brush: js notranslate">function multiply(a, b = 1) { +<pre class="brush: js">function multiply(a, b = 1) { return a*b; } @@ -527,7 +527,7 @@ multiply(5); // 5</pre> <p><a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/rest_parameters">剩余参数</a>语法允许将不确定数量的参数表示为数组。在下面的例子中,使用剩余参数收集从第二个到最后参数。然后,我们将这个数组的每一个数与第一个参数相乘。这个例子是使用了一个箭头函数,这将在下一节介绍。</p> -<pre class="brush: js notranslate">function multiply(multiplier, ...theArgs) { +<pre class="brush: js">function multiply(multiplier, ...theArgs) { return theArgs.map(x => multiplier * x); } @@ -544,7 +544,7 @@ console.log(arr); // [2, 4, 6]</pre> <p>在一些函数模式中,更简洁的函数很受欢迎。对比一下:</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var a = [ +<pre class="brush: js line-numbers language-js"><code class="language-js">var a = [ "Hydrogen", "Helium", "Lithium", @@ -563,7 +563,7 @@ console.log(a3); // logs [ 8, 6, 7, 9 ]</code></pre> <p>在箭头函数出现之前,每一个新函数都重新定义了自己的 <a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/this">this</a> 值(在构造函数中是一个新的对象;在严格模式下是未定义的;在作为“对象方法”调用的函数中指向这个对象;等等)。以面向对象的编程风格,这样着实有点恼人。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">function Person() { +<pre class="brush: js line-numbers language-js"><code class="language-js">function Person() { // 构造函数Person()将`this`定义为自身 this.age = 0; @@ -579,7 +579,7 @@ var p = new Person();</code></pre> <p>在ECMAScript 3/5里,通过把<code>this</code>的值赋值给一个变量可以修复这个问题。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">function Person() { +<pre class="brush: js line-numbers language-js"><code class="language-js">function Person() { var self = this; // 有的人习惯用`that`而不是`self`, // 无论你选择哪一种方式,请保持前后代码的一致性 self.age = 0; @@ -594,7 +594,7 @@ var p = new Person();</code></pre> <p>箭头函数捕捉闭包上下文的<code>this</code>值,所以下面的代码工作正常。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">function Person(){ +<pre class="brush: js line-numbers language-js"><code class="language-js">function Person(){ this.age = 0; setInterval(() => { diff --git a/files/zh-cn/web/javascript/guide/grammar_and_types/index.html b/files/zh-cn/web/javascript/guide/grammar_and_types/index.html index 9a3aa594c3..a5e540e163 100644 --- a/files/zh-cn/web/javascript/guide/grammar_and_types/index.html +++ b/files/zh-cn/web/javascript/guide/grammar_and_types/index.html @@ -21,7 +21,7 @@ translation_of: Web/JavaScript/Guide/Grammar_and_types <p>JavaScript 是<strong>区分大小写</strong>的,并使用 <strong>Unicode </strong>字符集。举个例子,可以将单词 Früh (在德语中意思是“早”)用作变量名。</p> -<pre class="notranslate"><code>var Früh = "foobar";</code></pre> +<pre><code>var Früh = "foobar";</code></pre> <p>但是,由于 JavaScript 是大小写敏感的,因此变量 <code>früh</code> 和 <code>Früh</code> 则是两个不同的变量。</p> @@ -35,7 +35,7 @@ translation_of: Web/JavaScript/Guide/Grammar_and_types <p><strong>Javascript 注释</strong>的语法和 C++ 或许多其他语言类似:</p> -<pre class="brush: js notranslate">// 单行注释 +<pre class="brush: js">// 单行注释 /* 这是一个更长的, 多行注释 @@ -84,7 +84,7 @@ translation_of: Web/JavaScript/Guide/Grammar_and_types <p>如果访问一个未声明的变量会导致抛出一个引用错误(ReferenceError)异常:</p> -<pre class="brush: js notranslate">var a; +<pre class="brush: js">var a; console.log("The value of a is " + a); // a 的值是 undefined console.log("The value of b is " + b);// b 的值是 undefined @@ -101,7 +101,7 @@ let y;</pre> <p>你可以使用 <code>undefined</code> 来判断一个变量是否已赋值。在以下的代码中,变量<code>input</code>未被赋值,因此 <code><a 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 notranslate">var input; +<pre class="brush: js">var input; if(input === undefined){ doThis(); } else { @@ -111,19 +111,19 @@ if(input === undefined){ <p><code>The following is related to "Variables" section as potential values in assignment.undefined</code> 值在布尔类型环境中会被当作 <code>false</code> 。例如,下面的代码将会执行函数 <code>myFunction</code>,因为数组 <code>myArray</code> 中的元素未被赋值:</p> -<pre class="brush: js notranslate">var myArray = []; +<pre class="brush: js">var myArray = []; if (!myArray[0]) myFunction(); </pre> <p>数值类型环境中 <code>undefined</code> 值会被转换为 <code>NaN</code>。</p> -<pre class="brush: js notranslate">var a; +<pre class="brush: js">var a; a + 2; // 计算为 NaN </pre> <p>当你对一个 <code>null</code> 变量求值时,空值 <code>null</code> 在数值类型环境中会被当作0来对待,而布尔类型环境中会被当作 <code>false</code>。例如:</p> -<pre class="brush: js notranslate">var n = null; +<pre class="brush: js">var n = null; console.log(n * 32); // 在控制台中会显示 0 </pre> @@ -133,7 +133,7 @@ console.log(n * 32); // 在控制台中会显示 0 <p>ECMAScript 6 之前的 JavaScript 没有 <a href="https://developer.mozilla.org/zh-CN/docs/JavaScript/Guide/Statements#Block_Statement">语句块</a> 作用域;相反,语句块中声明的变量将成为语句块所在函数(或全局作用域)的局部变量。例如,如下的代码将在控制台输出 5,因为 <code>x</code> 的作用域是声明了 <code>x</code> 的那个函数(或全局范围),而不是 <code>if</code> 语句块。</p> -<pre class="brush: js notranslate">if (true) { +<pre class="brush: js">if (true) { var x = 5; } console.log(x); // 5 @@ -141,7 +141,7 @@ console.log(x); // 5 <p>如果使用 ECMAScript 6 中的 <code>let</code> 声明,上述行为将发生变化。</p> -<pre class="brush: js notranslate">if (true) { +<pre class="brush: js">if (true) { let y = 5; } console.log(y); // ReferenceError: y 没有被声明</pre> @@ -150,7 +150,7 @@ console.log(y); // ReferenceError: y 没有被声明</pre> <p>JavaScript 变量的另一个不同寻常的地方是,你可以先使用变量稍后再声明变量而不会引发异常。这一概念称为变量提升;JavaScript 变量感觉上是被“提升”或移到了函数或语句的最前面。但是,提升后的变量将返回 undefined 值。因此在使用或引用某个变量之后进行声明和初始化操作,这个被提升的变量仍将返回 undefined 值。</p> -<pre class="brush: js notranslate">/** +<pre class="brush: js">/** * 例子1 */ console.log(x === undefined); // true @@ -171,7 +171,7 @@ var myvar = "my value"; <p>上面的例子,也可写作:</p> -<pre class="brush: js notranslate">/** +<pre class="brush: js">/** * 例子1 */ var x; @@ -193,14 +193,14 @@ var myvar = "my value"; <p>在 ECMAScript 6 中,let(const)同样<strong>会被提升</strong>变量到代码块的顶部但是不会被赋予初始值。在变量声明之前引用这个变量,将抛出引用错误(ReferenceError)。这个变量将从代码块一开始的时候就处在一个“暂时性死区”,直到这个变量被声明为止。</p> -<pre class="brush: js notranslate">console.log(x); // ReferenceError +<pre class="brush: js">console.log(x); // ReferenceError let x = 3;</pre> <h3 id="函数提升">函数提升</h3> <p>对于函数来说,只有函数声明会被提升到顶部,而函数表达式不会被提升。</p> -<pre class="brush: js notranslate">/* 函数声明 */ +<pre class="brush: js">/* 函数声明 */ foo(); // "bar" @@ -227,7 +227,7 @@ var baz = function() { <p>你可以用关键字 <code>const</code> 创建一个只读的常量。常量标识符的命名规则和变量相同:必须以字母、下划线(_)或美元符号($)开头并可以包含有字母、数字或下划线。</p> -<pre class="brush: js notranslate">const PI = 3.14; +<pre class="brush: js">const PI = 3.14; </pre> <p>常量不可以通过重新赋值改变其值,也不可以在代码运行时重新声明。它必须被初始化为某个值。</p> @@ -236,7 +236,7 @@ var baz = function() { <p>在同一作用域中,不能使用与变量名或函数名相同的名字来命名常量。例如:</p> -<pre class="brush: js notranslate">// 这会造成错误 +<pre class="brush: js">// 这会造成错误 function f() {}; const f = 5; @@ -251,12 +251,12 @@ function f() { <p>然而,对象属性被赋值为常量是不受保护的,所以下面的语句执行时不会产生错误。</p> -<pre class="brush: js notranslate">const MY_OBJECT = {"key": "value"}; +<pre class="brush: js">const MY_OBJECT = {"key": "value"}; MY_OBJECT.key = "otherValue";</pre> <p>同样的,数组的被定义为常量也是不受保护的,所以下面的语句执行时也不会产生错误。</p> -<pre class="brush: js notranslate">const MY_ARRAY = ['HTML','CSS']; +<pre class="brush: js">const MY_ARRAY = ['HTML','CSS']; MY_ARRAY.push('JAVASCRIPT'); console.log(MY_ARRAY); //logs ['HTML','CSS','JAVASCRIPT']; </pre> @@ -288,24 +288,24 @@ console.log(MY_ARRAY); //logs ['HTML','CSS','JAVASCRIPT']; <p>JavaScript是一种动态类型语言(dynamically typed language)。这意味着你在声明变量时可以不必指定数据类型,而数据类型会在代码执行时会根据需要自动转换。因此,你可以按照如下方式来定义变量:</p> -<pre class="brush: js notranslate">var answer = 42; +<pre class="brush: js">var answer = 42; </pre> <p>然后,你还可以给同一个变量赋予一个字符串值,例如:</p> -<pre class="brush: js notranslate">answer = "Thanks for all the fish...";</pre> +<pre class="brush: js">answer = "Thanks for all the fish...";</pre> <p>因为 JavaScript 是动态类型的,这种赋值方式并不会提示出错。</p> <p>在包含的数字和字符串的表达式中使用加法运算符(+),JavaScript 会把数字转换成字符串。例如,观察以下语句:</p> -<pre class="brush: js notranslate">x = "The answer is " + 42 // "The answer is 42" +<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 notranslate">"37" - 7 // 30 +<pre class="brush: js">"37" - 7 // 30 "37" + 7 // "377" </pre> @@ -321,7 +321,7 @@ y = 42 + " is the answer" // "42 is the answer" <p>将字符串转换为数字的另一种方法是使用一元<strong>加法运算符</strong>。</p> -<pre class="brush: js notranslate">"1.1" + "1.1" = "1.11.1" +<pre class="brush: js">"1.1" + "1.1" = "1.11.1" (+"1.1") + (+"1.1") = 2.2 // 注意:加入括号为清楚起见,不是必需的。 </pre> @@ -348,7 +348,7 @@ y = 42 + " is the answer" // "42 is the answer" <p>下面的示例用3个元素生成数组<code>coffees</code>,它的长度是3。</p> -<pre class="brush: js notranslate">var coffees = ["French Roast", "Colombian", "Kona"]; +<pre class="brush: js">var coffees = ["French Roast", "Colombian", "Kona"]; var a=[3]; @@ -368,7 +368,7 @@ console.log(a[0]); // 3</pre> <p>(译注:声明时)你不必列举数组字面值中的所有元素。若你在同一行中连写两个逗号(,),数组中就会产生一个没有被指定的元素,其初始值是<code>undefined</code>。以下示例创建了一个名为<code>fish</code>的数组:</p> -<pre class="brush: js notranslate">var fish = ["Lion", , "Angel"]; +<pre class="brush: js">var fish = ["Lion", , "Angel"]; </pre> <p>在这个数组中,有两个已被赋值的元素,和一个空元素(fish[0]是"Lion",fish[1]是undefined,而fish[2]是"Angel";译注:此时数组的长度属性fish.length是3)。</p> @@ -381,17 +381,17 @@ console.log(a[0]); // 3</pre> <p>(译注:而“现代”的浏览器似乎鼓励这种方式,这也很好解释原因。尾部逗号可以减少向数组的最后添加元素时,因为忘记为这最后一个元素加逗号 所造成的错误。)</p> -<pre class="brush: js notranslate">var myList = ['home', , 'school', ]; +<pre class="brush: js">var myList = ['home', , 'school', ]; </pre> <p>在下面的例子中,数组的长度是4,元素<code>myList[0]</code>和<code>myList[2]</code>缺失(译注:没被赋值,因而是undefined)。</p> -<pre class="brush: js notranslate">var myList = [ , 'home', , 'school']; +<pre class="brush: js">var myList = [ , 'home', , 'school']; </pre> <p>再看一个例子。在这里,该数组的长度是4,元素<code>myList[1]</code>和<code>myList[3]</code>被漏掉了。(但是)只有最后的那个逗号被忽略。</p> -<pre class="brush: js notranslate">var myList = ['home', , 'school', , ]; +<pre class="brush: js">var myList = ['home', , 'school', , ]; </pre> <p>理解多余的逗号(在脚本运行时会被如何处理)的含义,对于从语言层面理解JavaScript是十分重要的。但是,在你自己写代码时:<strong>显式地将缺失的元素声明为<code>undefined</code>,将大大提高你的代码的清晰度和可维护性</strong>。</p> @@ -421,7 +421,7 @@ console.log(a[0]); // 3</pre> <p>整数字面量举例:</p> -<pre class="notranslate"><code>0, 117 and -345 (十进制, 基数为10) +<pre><code>0, 117 and -345 (十进制, 基数为10) 015, 0001 and -0o77 (八进制, 基数为8) 0x1123, 0x00111 and -0xF1A7 (十六进制, 基数为16或"hex") 0b11, 0b0011 and -0b11 (二进制, 基数为2)</code></pre> @@ -441,11 +441,11 @@ console.log(a[0]); // 3</pre> <p>简言之,其语法是:</p> -<pre class="brush: js notranslate"><code class="language-html">[(+|-)][digits][.digits][(E|e)[(+|-)]digits]</code></pre> +<pre class="brush: js"><code class="language-html">[(+|-)][digits][.digits][(E|e)[(+|-)]digits]</code></pre> <p>例如:</p> -<pre class="brush: js notranslate">3.14 +<pre class="brush: js">3.14 -.2345789 // -0.23456789 -3.12e+12 // -3.12*10^12 .1e-23 // 0.1*10^(-23)=10^(-24)=1e-24 @@ -457,7 +457,7 @@ console.log(a[0]); // 3</pre> <p>以下是一个对象字面值的例子。对象car的第一个元素(译注:即一个属性/值对)定义了属性myCar;第二个元素,属性getCar,引用了一个函数(即CarTypes("Honda"));第三个元素,属性special,使用了一个已有的变量(即Sales)。</p> -<pre class="brush: js notranslate">var Sales = "Toyota"; +<pre class="brush: js">var Sales = "Toyota"; function CarTypes(name) { return (name === "Honda") ? @@ -474,7 +474,7 @@ console.log(car.special); // Toyota <p>更进一步的,你可以使用数字或字符串字面值作为属性的名字,或者在另一个字面值内嵌套上一个字面值。如下的示例中使用了这些可选项。</p> -<pre class="brush: js notranslate">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; +<pre class="brush: js">var car = { manyCars: {a: "Saab", "b": "Jeep"}, 7: "Mazda" }; console.log(car.manyCars.b); // Jeep console.log(car[7]); // Mazda @@ -482,7 +482,7 @@ console.log(car[7]); // Mazda <p>对象属性名字可以是任意字符串,包括空串。如果对象属性名字不是合法的javascript标识符,它必须用""包裹。属性的名字不合法,那么便不能用.访问属性值,而是通过类数组标记("[]")访问和赋值。</p> -<pre class="brush: js notranslate">var unusualPropertyNames = { +<pre class="brush: js">var unusualPropertyNames = { "": "An empty string", "!": "Bang!" } @@ -495,7 +495,7 @@ console.log(unusualPropertyNames["!"]); // Bang!</pre> <p>在ES2015,对象字面值扩展支持在创建时设置原型,简写了 foo: foo 形式的属性赋值,方法定义,支持父方法调用,以及使用表达式动态计算属性名。总之,这些也使对象字面值和类声明更加紧密地联系起来,让基于对象的设计从这些便利中更加受益。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var obj = { +<pre class="brush: js line-numbers language-js"><code class="language-js">var obj = { // __proto__ __proto__: theProtoObj, // Shorthand for ‘handler: handler’ @@ -511,7 +511,7 @@ console.log(unusualPropertyNames["!"]); // Bang!</pre> <p>请注意:</p> -<pre class="brush: js notranslate">var foo = {a: "alpha", 2: "two"}; +<pre class="brush: js">var foo = {a: "alpha", 2: "two"}; console.log(foo.a); // alpha console.log(foo[2]); // two //console.log(foo.2); // SyntaxError: missing ) after argument list @@ -523,13 +523,13 @@ console.log(foo["2"]); // two</pre> <p>一个正则表达式是字符被斜线(译注:正斜杠“/”)围成的表达式。下面是一个正则表达式文字的一个例子。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var re = /ab+c/;</code></pre> +<pre class="brush: js line-numbers language-js"><code class="language-js">var re = /ab+c/;</code></pre> <h3 id="字符串字面量_String_literals">字符串字面量 (String literals)</h3> <p>字符串字面量是由双引号(")对或单引号(')括起来的零个或多个字符。字符串被限定在同种引号之间;也即,必须是成对单引号或成对双引号。下面的例子都是字符串字面值:</p> -<pre class="brush: js notranslate">"foo" +<pre class="brush: js">"foo" 'bar' "1234" "one line \n another line" @@ -537,13 +537,13 @@ console.log(foo["2"]); // two</pre> <p>你可以在字符串字面值上使用字符串对象的所有方法——JavaScript会自动将字符串字面值转换为一个临时字符串对象,调用该方法,然后废弃掉那个临时的字符串对象。你也能用对字符串字面值使用类似String.length的属性:</p> -<pre class="brush: js notranslate"><code>console.log("John's cat".length) +<pre class="brush: js"><code>console.log("John's cat".length) // 将打印字符串中的字符个数(包括空格) // 结果为:10</code></pre> <p>在ES2015中,还提供了一种模板字面量(template literals),模板字符串提供了一些语法糖来帮你构造字符串。这与Perl、Python还有其他语言中的字符串插值(string interpolation)的特性非常相似。除此之外,你可以在通过模板字符串前添加一个tag来自定义模板字符串的解析过程,这可以用来防止注入攻击,或者用来建立基于字符串的高级数据抽象。</p> -<pre class="brush: js notranslate">// Basic literal string creation +<pre class="brush: js">// Basic literal string creation `In JavaScript '\n' is a line-feed.` // Multiline strings @@ -568,7 +568,7 @@ POST`http://foo.org/bar?a=${a}&b=${b} <p>作为一般字符的扩展,你可以在字符串中使用特殊字符,如下例所示。</p> -<pre class="brush: js notranslate">"one line \n another line" +<pre class="brush: js">"one line \n another line" </pre> <p>以下表格列举了你能在JavaScript的字符串中使用的特殊字符。</p> @@ -649,23 +649,23 @@ POST`http://foo.org/bar?a=${a}&b=${b} <p>通过在引号前加上反斜线'\',可以在字符串中插入引号,这就是<em>引号转义</em>。例如:</p> -<pre class="brush: js notranslate">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; +<pre class="brush: js">var quote = "He read \"The Cremation of Sam McGee\" by R.W. Service."; console.log(quote); </pre> <p>代码的运行结果为:</p> -<pre class="brush: js notranslate">He read "The Cremation of Sam McGee" by R.W. Service. +<pre class="brush: js">He read "The Cremation of Sam McGee" by R.W. Service. </pre> <p>要在字符串中插入'\'字面值,必须转义反斜线。例如,要把文件路径 c:\temp 赋值给一个字符串,可以采用如下方式:</p> -<pre class="brush: js notranslate">var home = "c:\\temp"; +<pre class="brush: js">var home = "c:\\temp"; </pre> <p>也可以在换行之前加上反斜线以转义换行(译注:实际上就是一条语句拆成多行书写),这样反斜线和换行都不会出现在字符串的值中。</p> -<pre class="brush: js notranslate">var str = "this string \ +<pre class="brush: js">var str = "this string \ is broken \ across multiple\ lines." @@ -674,7 +674,7 @@ console.log(str); // this string is broken across multiplelines. <p>Javascript没有“heredoc”语法,但可以用行末的换行符转义和转义的换行来近似实现 </p> -<pre class="brush: js notranslate">var poem = +<pre class="brush: js">var poem = "Roses are red,\n\ Violets are blue.\n\ Sugar is sweet,\n\ @@ -683,7 +683,7 @@ and so is foo." <p>ECMAScript 2015 增加了一种新的字面量,叫做模板字面量 <strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings" rel="noreferrer">template literals</a>。</strong>它包含一些新特征,包括了多行字符串!</p> -<pre class="brush: js notranslate">var poem = +<pre class="brush: js">var poem = `Roses are red, Violets are blue. Sugar is sweet, diff --git a/files/zh-cn/web/javascript/guide/indexed_collections/index.html b/files/zh-cn/web/javascript/guide/indexed_collections/index.html index fae44cbb84..600ec4ed4e 100644 --- a/files/zh-cn/web/javascript/guide/indexed_collections/index.html +++ b/files/zh-cn/web/javascript/guide/indexed_collections/index.html @@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Guide/Indexed_collections <p>以下语句创建等效的数组:</p> -<pre class="brush: js notranslate">var arr = new Array(element0, element1, ..., elementN); +<pre class="brush: js">var arr = new Array(element0, element1, ..., elementN); var arr = Array(element0, element1, ..., elementN); var arr = [element0, element1, ..., elementN]; @@ -30,7 +30,7 @@ var arr = [element0, element1, ..., elementN]; <p>为了创建一个长度不为0,但是又没有任何元素的数组,可选以下任何一种方式:</p> -<pre class="brush: js notranslate">var arr = new Array(arrayLength); +<pre class="brush: js">var arr = new Array(arrayLength); var arr = Array(arrayLength); // 这样有同样的效果 @@ -44,7 +44,7 @@ arr.length = arrayLength; <p>除了如上所示创建新定义的变量,数组(array)也可以作为一个属性(property)分配给一个新的或者已存在的对象(object):</p> -<pre class="brush: js notranslate">var obj = {}; +<pre class="brush: js">var obj = {}; // ... obj.prop = [element0, element1, ..., elementN]; @@ -54,7 +54,7 @@ var obj = {prop: [element0, element1, ...., elementN]} <p>如果你希望用单个元素初始化一个数组,而这个元素恰好又是数字(<code>Number</code>),那么你必须使用括号语法。当单个的数字(<code>Number</code>)传递给Array()构造函数时,将会被解释为数组长度,并非单个元素。</p> -<pre class="brush: js notranslate">var arr = [42]; // 创建一个只有唯一元素的数组: +<pre class="brush: js">var arr = [42]; // 创建一个只有唯一元素的数组: // the <strong>number</strong> 42. var arr = Array(42); // 创建一个没有元素的数组, // 但是数组的长度被设置成42. @@ -66,7 +66,7 @@ arr.length = 42; <p>如果N不是一个整数,调用<code>Array(N)</code>将会报<code>RangeError</code>错误, 以下方法说明了这种行为:</p> -<pre class="brush: js notranslate">var arr = Array(9.3); // RangeError: Invalid array length +<pre class="brush: js">var arr = Array(9.3); // RangeError: Invalid array length </pre> <p>如果你需要创建任意类型的单元素数组,安全的方式是使用字面值。或者在向数组添加单个元素之前先创建一个空的数组。</p> @@ -75,7 +75,7 @@ arr.length = 42; <p>你可以通过给元素赋值来填充数组,例如:</p> -<pre class="brush: js notranslate">var emp = []; +<pre class="brush: js">var emp = []; emp[0] = "Casey Jones"; emp[1] = "Phil Lesh"; emp[2] = "August West"; @@ -85,7 +85,7 @@ emp[2] = "August West"; <p><strong>注意:</strong>如果你在以上代码中给数组操作符的是一个非整形数值,那么将作为一个代表数组的对象的属性(property)创建,而非作为数组的元素。</p> </div> -<pre class="brush: js notranslate">var arr = []; +<pre class="brush: js">var arr = []; arr[3.4] = "Oranges"; console.log(arr.length); // 0 console.log(arr.hasOwnProperty(3.4)); // true @@ -93,7 +93,7 @@ console.log(arr.hasOwnProperty(3.4)); // true <p>你也可以在创建数组的时候去填充它:</p> -<pre class="brush: js notranslate">var myArray = new Array("Hello", myVar, 3.14159); +<pre class="brush: js">var myArray = new Array("Hello", myVar, 3.14159); var myArray = ["Mango", "Apple", "Orange"] </pre> @@ -101,7 +101,7 @@ var myArray = ["Mango", "Apple", "Orange"] <p>您通过可以使用元素的序号来引用数组的元素。例如,假设你定义了如下数组:</p> -<pre class="brush: js notranslate">var myArray = ["Wind", "Rain", "Fire"]; +<pre class="brush: js">var myArray = ["Wind", "Rain", "Fire"]; </pre> <p>你可以用 <code>myArray[0]</code>引用第一个元素,<code>myArray[1]</code>引用第二个元素。元素的索引是从<code>0</code>开始的。</p> @@ -110,7 +110,7 @@ var myArray = ["Mango", "Apple", "Orange"] <p><strong>注意:</strong>数组操作符(方括号 [ ])也可以用来访问数组的属性(在 JavaScript 中,数组也是对象)。例如:</p> </div> -<pre class="brush: js notranslate">var arr = ["one", "two", "three"]; +<pre class="brush: js">var arr = ["one", "two", "three"]; arr[2]; // three arr["length"]; // 3 </pre> @@ -119,14 +119,14 @@ arr["length"]; // 3 <p>在实施层面, JavaScript实际上是将元素作为标准的对象属性来存储,把数组索引作为属性名。长度属性是特殊的,它总是返回最后一个元素的索引值加1(下例中, Dusty 的索引是30,所以cats.length 返回 30 + 1)。记住, JavaScript 数组索引是基于0的: 他们从0开始,而不是1。这意味着数组长度属性将比最大的索引值大1:</p> -<pre class="brush: js notranslate">var cats = []; +<pre class="brush: js">var cats = []; cats[30] = ['Dusty']; console.log(cats.length); // 31 </pre> <p>你也可以分配<code>length</code>属性。写一个小于数组元素数量的值会缩短数组,写0会彻底清空数组:</p> -<pre class="brush: js notranslate">var cats = ['Dusty', 'Misty', 'Twiggy']; +<pre class="brush: js">var cats = ['Dusty', 'Misty', 'Twiggy']; console.log(cats.length); // 3 cats.length = 2; @@ -143,7 +143,7 @@ console.log(cats); // [undefined, undefined, undefined] <p>遍历数组元素并以某种方式处理每个元素是一个常见的操作。以下是最简单的方式:</p> -<pre class="brush: js notranslate">var colors = ['red', 'green', 'blue']; +<pre class="brush: js">var colors = ['red', 'green', 'blue']; for (var i = 0; i < colors.length; i++) { console.log(colors[i]); } @@ -151,7 +151,7 @@ for (var i = 0; i < colors.length; i++) { <p>如果你确定数组中没有一个元素的求值是false —— 如果你的数组只包含<a href="/en-US/docs/DOM" title="en-US/docs/DOM">DOM</a>节点,如下,你可以选择一个更高效的土法子:</p> -<pre class="brush: js notranslate">var divs = document.getElementsByTagName('div'); +<pre class="brush: js">var divs = document.getElementsByTagName('div'); for (var i = 0, div; div = divs[i]; i++) { /* Process div in some way */ } @@ -161,7 +161,7 @@ for (var i = 0, div; div = divs[i]; i++) { <p>{{jsxref("Array.forEach", "forEach()")}} 方法提供了遍历数组元素的其他方法:</p> -<pre class="brush: js notranslate">var colors = ['red', 'green', 'blue']; +<pre class="brush: js">var colors = ['red', 'green', 'blue']; colors.forEach(function(color) { console.log(color); }); @@ -171,7 +171,7 @@ colors.forEach(function(color) { <p>注意,在数组定义时省略的元素不会在forEach遍历时被列出,但是手动赋值为undefined的元素是会被列出的:</p> -<pre class="brush: js notranslate">var array = ['first', 'second', , 'fourth']; +<pre class="brush: js">var array = ['first', 'second', , 'fourth']; // returns ['first', 'second', 'fourth']; array.forEach(function(element) { @@ -195,53 +195,53 @@ array.forEach(function(element) { <p>{{jsxref("Array.concat", "concat()")}} 连接两个数组并返回一个新的数组。</p> -<pre class="brush: js notranslate">var myArray = new Array("1", "2", "3"); +<pre class="brush: js">var myArray = new Array("1", "2", "3"); myArray = myArray.concat("a", "b", "c"); // myArray is now ["1", "2", "3", "a", "b", "c"] </pre> <p>{{jsxref("Array.join", "join(deliminator = ',')")}} 将数组的所有元素连接成一个字符串。</p> -<pre class="brush: js notranslate">var myArray = new Array("Wind", "Rain", "Fire"); +<pre class="brush: js">var myArray = new Array("Wind", "Rain", "Fire"); var list = myArray.join(" - "); // list is "Wind - Rain - Fire" </pre> <p>{{jsxref("Array.push", "push()")}} 在数组末尾添加一个或多个元素,并返回数组操作后的长度。</p> -<pre class="brush: js notranslate">var myArray = new Array("1", "2"); +<pre class="brush: js">var myArray = new Array("1", "2"); myArray.push("3"); // myArray is now ["1", "2", "3"] </pre> <p>{{jsxref("Array.pop", "pop()")}} 从数组移出最后一个元素,并返回该元素。</p> -<pre class="brush: js notranslate">var myArray = new Array("1", "2", "3"); +<pre class="brush: js">var myArray = new Array("1", "2", "3"); var last = myArray.pop(); // myArray is now ["1", "2"], last = "3" </pre> <p>{{jsxref("Array.shift", "shift()")}} 从数组移出第一个元素,并返回该元素。</p> -<pre class="brush: js notranslate">var myArray = new Array ("1", "2", "3"); +<pre class="brush: js">var myArray = new Array ("1", "2", "3"); var first = myArray.shift(); // myArray is now ["2", "3"], first is "1" </pre> <p>{{jsxref("Array.shift", "unshift()")}} 在数组开头添加一个或多个元素,并返回数组的新长度。</p> -<pre class="brush: js notranslate">var myArray = new Array ("1", "2", "3"); +<pre class="brush: js">var myArray = new Array ("1", "2", "3"); myArray.unshift("4", "5"); // myArray becomes ["4", "5", "1", "2", "3"]</pre> <p>{{jsxref("Array.slice", "slice(start_index, upto_index)")}} 从数组提取一个片段,并作为一个新数组返回。</p> -<pre class="brush: js notranslate">var myArray = new Array ("a", "b", "c", "d", "e"); +<pre class="brush: js">var myArray = new Array ("a", "b", "c", "d", "e"); myArray = myArray.slice(1, 4); // 包含索引1,不包括索引4 // returning [ "b", "c", "d"] </pre> <p>{{jsxref("Array.splice", "splice(index, count_to_remove, addElement1, addElement2, ...)")}}从数组移出一些元素,(可选)并替换它们。</p> -<pre class="brush: js notranslate">var myArray = new Array ("1", "2", "3", "4", "5"); +<pre class="brush: js">var myArray = new Array ("1", "2", "3", "4", "5"); myArray.splice(1, 3, "a", "b", "c", "d"); // myArray is now ["1", "a", "b", "c", "d", "5"] // This code started at index one (or where the "2" was), @@ -251,14 +251,14 @@ myArray.splice(1, 3, "a", "b", "c", "d"); <p>{{jsxref("Array.reverse", "reverse()")}} 颠倒数组元素的顺序:第一个变成最后一个,最后一个变成第一个。</p> -<pre class="brush: js notranslate">var myArray = new Array ("1", "2", "3"); +<pre class="brush: js">var myArray = new Array ("1", "2", "3"); myArray.reverse(); // transposes the array so that myArray = [ "3", "2", "1" ] </pre> <p>{{jsxref("Array.sort", "sort()")}} 给数组元素排序。</p> -<pre class="brush: js notranslate">var myArray = new Array("Wind", "Rain", "Fire"); +<pre class="brush: js">var myArray = new Array("Wind", "Rain", "Fire"); myArray.sort(); // sorts the array so that myArray = [ "Fire", "Rain", "Wind" ] </pre> @@ -267,7 +267,7 @@ myArray.sort(); <p>例如,下面的代码通过字符串的最后一个字母进行排序:</p> -<pre class="brush: js notranslate">var sortFn = function(a, b){ +<pre class="brush: js">var sortFn = function(a, b){ if (a[a.length - 1] < b[b.length - 1]) return -1; if (a[a.length - 1] > b[b.length - 1]) return 1; if (a[a.length - 1] == b[b.length - 1]) return 0; @@ -283,7 +283,7 @@ myArray.sort(sortFn); <p>{{jsxref("Array.indexOf", "indexOf(searchElement[, fromIndex])")}} 在数组中搜索<code>searchElement</code> 并返回第一个匹配的索引。</p> -<pre class="brush: js notranslate">var a = ['a', 'b', 'a', 'b', 'a']; +<pre class="brush: js">var a = ['a', 'b', 'a', 'b', 'a']; console.log(a.indexOf('b')); // logs 1 // Now try again, starting from after the last match console.log(a.indexOf('b', 2)); // logs 3 @@ -292,7 +292,7 @@ console.log(a.indexOf('z')); // logs -1, because 'z' was not found <p>{{jsxref("Array.lastIndexOf", "lastIndexOf(searchElement[, fromIndex])")}} 和 <code>indexOf 差不多,但这是从结尾开始,并且是反向搜索。</code></p> -<pre class="brush: js notranslate">var a = ['a', 'b', 'c', 'd', 'a', 'b']; +<pre class="brush: js">var a = ['a', 'b', 'c', 'd', 'a', 'b']; console.log(a.lastIndexOf('b')); // logs 5 // Now try again, starting from before the last match console.log(a.lastIndexOf('b', 4)); // logs 1 @@ -301,28 +301,28 @@ console.log(a.lastIndexOf('z')); // logs -1 <p>{{jsxref("Array.forEach", "forEach(callback[, thisObject])")}} 在数组每个元素项上执行<code>callback</code>。</p> -<pre class="brush: js notranslate">var a = ['a', 'b', 'c']; +<pre class="brush: js">var a = ['a', 'b', 'c']; a.forEach(function(element) { console.log(element);} ); // logs each item in turn </pre> <p>{{jsxref("Array.map", "map(callback[, thisObject])")}} 在数组的每个单元项上执行callback函数,并把返回包含回调函数返回值的新数组(译者注:也就是遍历数组,并通过callback对数组元素进行操作,并将所有操作结果放入数组中并返回该数组)。</p> -<pre class="brush: js notranslate">var a1 = ['a', 'b', 'c']; +<pre class="brush: js">var a1 = ['a', 'b', 'c']; var a2 = a1.map(function(item) { return item.toUpperCase(); }); console.log(a2); // logs A,B,C </pre> <p>{{jsxref("Array.filter", "filter(callback[, thisObject])")}} 返回一个包含所有在回调函数上返回为true的元素的新数组(译者注:callback在这里担任的是过滤器的角色,当元素符合条件,过滤器就返回true,而filter则会返回所有符合过滤条件的元素)。</p> -<pre class="brush: js notranslate">var a1 = ['a', 10, 'b', 20, 'c', 30]; +<pre class="brush: js">var a1 = ['a', 10, 'b', 20, 'c', 30]; var a2 = a1.filter(function(item) { return typeof item == 'number'; }); console.log(a2); // logs 10,20,30 </pre> <p>{{jsxref("Array.every", "every(callback[, thisObject])")}} 当数组中每一个元素在callback上被返回true时就返回true(译者注:同上,every其实类似filter,只不过它的功能是判断是不是数组中的所有元素都符合条件,并且返回的是布尔值)。</p> -<pre class="brush: js notranslate">function isNumber(value){ +<pre class="brush: js">function isNumber(value){ return typeof value == 'number'; } var a1 = [1, 2, 3]; @@ -333,7 +333,7 @@ console.log(a2.every(isNumber)); // logs false <p>{{jsxref("Array.some", "some(callback[, thisObject])")}} 只要数组中有一项在callback上被返回true,就返回true(译者注:同上,类似every,不过前者要求都符合筛选条件才返回true,后者只要有符合条件的就返回true)。</p> -<pre class="brush: js notranslate">function isNumber(value){ +<pre class="brush: js">function isNumber(value){ return typeof value == 'number'; } var a1 = [1, 2, 3]; @@ -350,7 +350,7 @@ console.log(a3.some(isNumber)); // logs false <p>{{jsxref("Array.reduce", "reduce(callback[, initialValue])")}} 使用回调函数 <code>callback(firstValue, secondValue)</code> 把数组列表计算成一个单一值(译者注:他数组元素两两递归处理的方式把数组计算成一个值)</p> -<pre class="brush: js notranslate">var a = [10, 20, 30]; +<pre class="brush: js">var a = [10, 20, 30]; var total = a.reduce(function(first, second) { return first + second; }, 0); console.log(total) // Prints 60 </pre> @@ -365,7 +365,7 @@ console.log(total) // Prints 60 <p>以下代码创建了一个二维数组。</p> -<pre class="brush: js notranslate">var a = new Array(4); +<pre class="brush: js">var a = new Array(4); for (i = 0; i < 4; i++) { a[i] = new Array(4); for (j = 0; j < 4; j++) { @@ -376,7 +376,7 @@ for (i = 0; i < 4; i++) { <p>这个例子创建的数组拥有以下行数据:</p> -<pre class="notranslate">Row 0: [0,0] [0,1] [0,2] [0,3] +<pre>Row 0: [0,0] [0,1] [0,2] [0,3] Row 1: [1,0] [1,1] [1,2] [1,3] Row 2: [2,0] [2,1] [2,2] [2,3] Row 3: [3,0] [3,1] [3,2] [3,3] @@ -393,7 +393,7 @@ Objects/String/split">String.split()</a> 的返回值是一个数组。</code> <p>Array的原生(prototype)方法可以用来处理类似数组行为的对象,例如: :</p> -<pre class="brush: js notranslate">function printArguments() { +<pre class="brush: js">function printArguments() { Array.prototype.forEach.call(arguments, function(item) { console.log(item); }); @@ -401,7 +401,7 @@ Objects/String/split">String.split()</a> 的返回值是一个数组。</code> <p>Array的常规方法也可以用于处理字符串,因为它提供了序列访问字符转为数组的简单方法:</p> -<pre class="brush: js notranslate">Array.prototype.forEach.call("a string", function(chr) { +<pre class="brush: js">Array.prototype.forEach.call("a string", function(chr) { console.log(chr); });</pre> @@ -411,31 +411,31 @@ Objects/String/split">String.split()</a> 的返回值是一个数组。</code> <p>下面的推导式创建一个数字数组并且创建一个新的数组,数组的每个元素都是原来数值的两倍(译者注:这种形式类似于Python的列表推导式)。</p> -<pre class="brush: js notranslate">var numbers = [1, 2, 3, 4]; +<pre class="brush: js">var numbers = [1, 2, 3, 4]; var doubled = [for (i of numbers) i * 2]; console.log(doubled); // logs 2,4,6,8 </pre> <p>这跟下面的map()方法的操作是等价的。</p> -<pre class="brush: js notranslate">var doubled = numbers.map(function(i){return i * 2;}); +<pre class="brush: js">var doubled = numbers.map(function(i){return i * 2;}); </pre> <p>推导式也可以用来筛选满足条件表达式的元素. 下面的推导式用来筛选是2的倍数的元素:</p> -<pre class="brush: js notranslate">var numbers = [1, 2, 3, 21, 22, 30]; +<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30]; var evens = [i for (i of numbers) if (i % 2 === 0)]; console.log(evens); // logs 2,22,30 </pre> <p><code>filter()</code> 也可以达到相同的目的:</p> -<pre class="brush: js notranslate">var evens = numbers.filter(function(i){return i % 2 === 0;}); +<pre class="brush: js">var evens = numbers.filter(function(i){return i % 2 === 0;}); </pre> <p><code>map()</code> <code>和filter()</code> 类型的操作可以被组合(等效)为单个数组推导式。这里就有一个过滤出偶数,创建一个它的倍数数组的例子:</p> -<pre class="brush: js notranslate">var numbers = [1, 2, 3, 21, 22, 30]; +<pre class="brush: js">var numbers = [1, 2, 3, 21, 22, 30]; var doubledEvens = [i * 2 for (i of numbers) if (i % 2 === 0)]; console.log(doubledEvens); // logs 4,44,60 </pre> @@ -446,7 +446,7 @@ console.log(doubledEvens); // logs 4,44,60 <p>甚至字符串也可以用来作为输入; 实现filter或者map行为 (参考上面类似数组行为的对象)如下:</p> -<pre class="brush: js notranslate">var str = 'abcdef'; +<pre class="brush: js">var str = 'abcdef'; var consonantsOnlyStr = [c for (c of str) if (!(/[aeiouAEIOU]/).test(c)) ].join(''); // 'bcdf' var interpolatedZeros = [c+'0' for (c of str) ].join(''); // 'a0b0c0d0e0f0' </pre> diff --git a/files/zh-cn/web/javascript/guide/introduction/index.html b/files/zh-cn/web/javascript/guide/introduction/index.html index 8a6a283d5c..3848d00603 100644 --- a/files/zh-cn/web/javascript/guide/introduction/index.html +++ b/files/zh-cn/web/javascript/guide/introduction/index.html @@ -117,7 +117,7 @@ translation_of: Web/JavaScript/Guide/Introduction <p>控制台的工作方式与eval完全相同:返回最后输入的表达式。为了简单起见,可以想象每次输入到控制台的东西实际上都被 console.log 所包围。</p> -<pre class="notranslate">function greetMe(yourName) { alert('Hello ' + yourName); } <code>console.log(eval('3 + 5'));</code></pre> +<pre>function greetMe(yourName) { alert('Hello ' + yourName); } <code>console.log(eval('3 + 5'));</code></pre> <h3 id="代码草稿纸(Scratchpad)">代码草稿纸(Scratchpad)</h3> @@ -133,7 +133,7 @@ translation_of: Web/JavaScript/Guide/Introduction <p>学习JavaScript 的第一步,打开浏览器的代码草稿纸尝试编写你的第一个 JavaScript 版本的 “Hello world” 程序。</p> -<pre class="brush: js notranslate">function greetMe(user) { +<pre class="brush: js">function greetMe(user) { alert('Hi ' + user); } diff --git a/files/zh-cn/web/javascript/guide/meta_programming/index.html b/files/zh-cn/web/javascript/guide/meta_programming/index.html index 723165c93f..65747f4058 100644 --- a/files/zh-cn/web/javascript/guide/meta_programming/index.html +++ b/files/zh-cn/web/javascript/guide/meta_programming/index.html @@ -16,7 +16,7 @@ translation_of: Web/JavaScript/Guide/Meta_programming <p>在 ECMAScript 6 中引入的 {{jsxref("Proxy")}} 对象可以拦截某些操作并实现自定义行为。例如获取一个对象上的属性:</p> -<pre class="brush: js notranslate">let handler = { +<pre class="brush: js">let handler = { get: function(target, name){ return name in target ? target[name] : 42; }}; @@ -204,7 +204,7 @@ console.log(p.a, p.b); // 1, 42 <p>{{jsxref("Proxy.revocable()")}} 方法被用来创建可撤销的 <code>Proxy</code> 对象。这意味着 proxy 可以通过 <code>revoke</code> 函数来撤销,并且关闭代理。此后,代理上的任意的操作都会导致{{jsxref("TypeError")}}。</p> -<pre class="brush: js notranslate">var revocable = Proxy.revocable({}, { +<pre class="brush: js">var revocable = Proxy.revocable({}, { get: function(target, name) { return "[[" + name + "]]"; } @@ -227,18 +227,18 @@ typeof proxy // "object", typeof doesn't trigger any trap</pre> <p>以 {{jsxref("Reflect.has()")}} 为例,你可以将 <a href="/en-US/docs/Web/JavaScript/Reference/Operators/in"><code>in</code> 运算符</a>作为函数:</p> -<pre class="brush: js notranslate">Reflect.has(Object, "assign"); // true +<pre class="brush: js">Reflect.has(Object, "assign"); // true </pre> <h3 id="更好的_apply_函数">更好的 <code>apply</code> 函数</h3> <p>在 ES5 中,我们通常使用 {{jsxref("Function.prototype.apply()")}} 方法调用一个具有给定 <code>this</code> 值和 <code>arguments</code> 数组(或<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Indexed_collections#Working_with_array-like_objects">类数组对象</a>)的函数。</p> -<pre class="brush: js notranslate">Function.prototype.apply.call(Math.floor, undefined, [1.75]);</pre> +<pre class="brush: js">Function.prototype.apply.call(Math.floor, undefined, [1.75]);</pre> <p>使用 {{jsxref("Reflect.apply")}},这变得不那么冗长和容易理解:</p> -<pre class="brush: js notranslate">Reflect.apply(Math.floor, undefined, [1.75]); +<pre class="brush: js">Reflect.apply(Math.floor, undefined, [1.75]); // 1; Reflect.apply(String.fromCharCode, undefined, [104, 101, 108, 108, 111]); @@ -254,7 +254,7 @@ Reflect.apply(''.charAt, 'ponies', [3]); <p>使用 {{jsxref("Object.defineProperty")}},如果成功返回一个对象,否则抛出一个 {{jsxref("TypeError")}},你将使用 {{jsxref("Statements/try...catch","try...catch")}} 块来捕获定义属性时发生的任何错误。因为 {{jsxref("Reflect.defineProperty")}} 返回一个布尔值表示的成功状态,你可以在这里使用 {{jsxref("Statements/if...else","if...else")}} 块:</p> -<pre class="brush: js notranslate">if (Reflect.defineProperty(target, property, attributes)) { +<pre class="brush: js">if (Reflect.defineProperty(target, property, attributes)) { // success } else { // failure diff --git a/files/zh-cn/web/javascript/guide/numbers_and_dates/index.html b/files/zh-cn/web/javascript/guide/numbers_and_dates/index.html index 48a950b5ed..79bdc48877 100644 --- a/files/zh-cn/web/javascript/guide/numbers_and_dates/index.html +++ b/files/zh-cn/web/javascript/guide/numbers_and_dates/index.html @@ -26,7 +26,7 @@ translation_of: Web/JavaScript/Guide/Numbers_and_dates <h3 id="十进制数字Decimal_numbers">十进制数字(Decimal numbers)</h3> -<pre class="brush: js notranslate">1234567890 +<pre class="brush: js">1234567890 42 // 以零开头的数字的注意事项: 0888 // 888 将被当做十进制处理 @@ -39,7 +39,7 @@ translation_of: Web/JavaScript/Guide/Numbers_and_dates <p>二进制数字语法是以零为开头,后面接一个小写或大写的拉丁文字母B(<code>0b或者是0B</code>)。 假如0b后面的数字不是0或者1,那么就会提示这样的语法错误( <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a>):</code> "Missing binary digits after 0b(0b之后缺失二有效的二进制数据)"。</p> -<pre class="brush: js notranslate">var FLT_SIGNBIT = 0b10000000000000000000000000000000; // 2147483648 +<pre class="brush: js">var FLT_SIGNBIT = 0b10000000000000000000000000000000; // 2147483648 var FLT_EXPONENT = 0b01111111100000000000000000000000; // 2139095040 var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607</pre> @@ -47,26 +47,26 @@ var FLT_MANTISSA = 0B00000000011111111111111111111111; // 8388607</pre> <p>八进制数字语法是以0为开头的。假如0后面的数字不在0到7的范围内,该数字将会被转换成十进制数字。</p> -<pre class="brush: js notranslate">var n = 0755; // 493 +<pre class="brush: js">var n = 0755; // 493 var m = 0644; // 420 </pre> <p>在ECMAScript 5 严格模式下禁止使用八进制语法。八进制语法并不是ECMAScript 5规范的一部分,但是通过在八进制数字添加一个前缀0就可以被所有的浏览器支持:0644 === 420 而且 "\045" === "%"。在ECMAScript 6中使用八进制数字是需要给一个数字添加前缀"0o"。</p> -<pre class="brush: js notranslate">var a = 0o10; // ES6 :八进制</pre> +<pre class="brush: js">var a = 0o10; // ES6 :八进制</pre> <h3 id="十六进制Hexadecimal_numbers">十六进制(Hexadecimal numbers)</h3> <p>十六进制数字语法是以零为开头,后面接一个小写或大写的拉丁文字母X(<code>0x或者是0X</code>)。假如<code>0x</code>后面的数字超出规定范围(0123456789ABCDEF),那么就会提示这样的语法错误(<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a>):</code>"Identifier starts immediately after numeric literal".</p> -<pre class="brush: js notranslate">0xFFFFFFFFFFFFFFFFF // 295147905179352830000 +<pre class="brush: js">0xFFFFFFFFFFFFFFFFF // 295147905179352830000 0x123456789ABCDEF // 81985529216486900 0XA // 10 </pre> <h3 id="指数形式Exponentiation">指数形式(Exponentiation)</h3> -<pre class="brush: js notranslate">1E3 // 1000 +<pre class="brush: js">1E3 // 1000 2e6 // 2000000 0.1e2 // 10 </pre> @@ -75,7 +75,7 @@ var m = 0644; // 420 <p>内置的{{jsxref("Number")}}对象有一些有关数字的常量属性,如最大值、不是一个数字和无穷大的。你不能改变这些属性,但可以按下边的方式使用它们:</p> -<pre class="brush: js notranslate">var biggestNum = Number.MAX_VALUE; +<pre class="brush: js">var biggestNum = Number.MAX_VALUE; var smallestNum = Number.MIN_VALUE; var infiniteNum = Number.POSITIVE_INFINITY; var negInfiniteNum = Number.NEGATIVE_INFINITY; @@ -210,12 +210,12 @@ var notANum = Number.NaN; <p>对于内置的{{jsxref("Math")}}数学常项和函数也有一些属性和方法。 比方说, <code>Math对象的</code> <code>PI</code> 属性会有属性值 pi (3.141...),你可以像这样调用它:</p> -<pre class="brush: js notranslate">Math.PI // π +<pre class="brush: js">Math.PI // π </pre> <p>同理,标准数学函数也是Math的方法。 这些包括三角函数,对数,指数,和其他函数。比方说你想使用三角函数 <code>sin</code>, 你可以这么写:</p> -<pre class="brush: js notranslate">Math.sin(1.56) +<pre class="brush: js">Math.sin(1.56) </pre> <p>需要注意的是Math的所有三角函数参数都是弧度制。</p> @@ -312,7 +312,7 @@ var notANum = Number.NaN; <p>创建一个日期对象:</p> -<pre class="brush: js notranslate">var dateObjectName = new Date([parameters]); +<pre class="brush: js">var dateObjectName = new Date([parameters]); </pre> <p>这里的 dateObjectName 对象是所创建的Date对象的一个名字,它可以成为一个新的对象或者已存在的其他对象的一个属性。</p> @@ -352,7 +352,7 @@ var notANum = Number.NaN; <p>例如, 假设你定义了如下日期:</p> -<pre class="brush: js notranslate">var Xmas95 = new Date("December 25, 1995"); +<pre class="brush: js">var Xmas95 = new Date("December 25, 1995"); </pre> <p>Then <code>Xmas95.getMonth()</code> 返回 11, and <code>Xmas95.getFullYear()</code> 返回 1995.</p> @@ -361,7 +361,7 @@ var notANum = Number.NaN; <p>例如,以下代码展示了今年剩下的天数:</p> -<pre class="brush: js notranslate">var today = new Date(); +<pre class="brush: js">var today = new Date(); var endYear = new Date(1995, 11, 31, 23, 59, 59, 999); // 设置日和月,注意,月份是0-11 endYear.setFullYear(today.getFullYear()); // 把年设置为今年 var msPerDay = 24 * 60 * 60 * 1000; // 每天的毫秒数 @@ -373,7 +373,7 @@ var daysLeft = Math.round(daysLeft); //返回今年剩下的天数 <p>parse方法对于从日期字符串赋值给现有的Date对象很有用,例如:以下代码使用<code>parse</code>和<code>setTime</code>分配了一个日期值给<code>IPOdate</code>对象:</p> -<pre class="brush: js notranslate">var IPOdate = new Date(); +<pre class="brush: js">var IPOdate = new Date(); IPOdate.setTime(Date.parse("Aug 9, 1995")); </pre> @@ -381,7 +381,7 @@ IPOdate.setTime(Date.parse("Aug 9, 1995")); <p>在下边的例子中,JSClock()函数返回了用数字时钟格式的时间:</p> -<pre class="brush: js notranslate">function JSClock() { +<pre class="brush: js">function JSClock() { var time = new Date(); var hour = time.getHours(); var minute = time.getMinutes(); diff --git a/files/zh-cn/web/javascript/guide/regular_expressions/assertions/index.html b/files/zh-cn/web/javascript/guide/regular_expressions/assertions/index.html index b7468ef5be..0d3757acd6 100644 --- a/files/zh-cn/web/javascript/guide/regular_expressions/assertions/index.html +++ b/files/zh-cn/web/javascript/guide/regular_expressions/assertions/index.html @@ -140,7 +140,7 @@ translation_of: Web/JavaScript/Guide/Regular_Expressions/Assertions <h3 id="一般边界类型概述示例">一般边界类型概述示例</h3> -<pre class="notranslate">// 使用 正则表达式边界修复错误字符串 +<pre>// 使用 正则表达式边界修复错误字符串 buggyMultiline = `tey, ihe light-greon apple tangs on ihe greon traa`; @@ -164,7 +164,7 @@ console.log(4, fixedMultiline); // 修复 'greon' 不影响'on'.</pre> <p>使用 <code>^</code>匹配输入的开头。在这个例子中,我们可以通过 /^A/ 正则表达式得到以A开头的水果。为了选择合适的水果,我们可以使用带有箭头函数的过滤方法.</p> -<pre class="notranslate">let fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"]; +<pre>let fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"]; // 使用正则 /^A/ 选择以'A'开头的水果. // 这里的 '^' 只有一种含义: 匹配输入的开头. @@ -174,7 +174,7 @@ console.log(fruitsStartsWithA); // [ 'Apple', 'Avocado' ]</pre> <p>在第二个示例中,^用于在输入的开始处匹配,以及在内部使用时用于创建否定或被补充的字符集 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges">组和范围</a>.</p> -<pre class="notranslate">let fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"]; +<pre>let fruits = ["Apple", "Watermelon", "Orange", "Avocado", "Strawberry"]; // 使用正则 /^[^A]/ 选择 不是以 ‘A’ 开头的水果 // 在这个例子中,“^” 控件符号表示两种含义: @@ -187,7 +187,7 @@ console.log(fruitsStartsWithNotA); // [ 'Watermelon', 'Orange', 'Strawberry' ]</ <h3 id="匹配字边界">匹配字边界</h3> -<pre class="notranslate">let fruitsWithDescription = ["Red apple", "Orange orange", "Green Avocado"]; +<pre>let fruitsWithDescription = ["Red apple", "Orange orange", "Green Avocado"]; // 选择包含以 “en” 或 “ed” 结尾的单词的描述: let enEdSelection = fruitsWithDescription.filter(descr => /(en|ed)\b/.test(descr)); @@ -196,7 +196,7 @@ console.log(enEdSelection); // [ 'Red apple', 'Green Avocado' ]</pre> <h3 id="向前断言">向前断言</h3> -<pre class="notranslate">// JS 向前断言 x(?=y) 匹配被 y 跟随的 x +<pre>// JS 向前断言 x(?=y) 匹配被 y 跟随的 x let regex = /First(?= test)/g; @@ -209,13 +209,13 @@ console.log('This is a First peach in a month.'.match(regex)); // null</pre> <p>例如, <code>/\d+(?!\.)/</code> 匹配没有被小数点跟随且至少有一位的数字。 <code>/\d+(?!\.)/.exec('3.141')</code> 匹配 "141" 而不是 "3" </p> -<pre class="notranslate">console.log(/\d+(?!\.)/g.exec('3.141')); // [ '141', index: 2, input: '3.141' ]</pre> +<pre>console.log(/\d+(?!\.)/g.exec('3.141')); // [ '141', index: 2, input: '3.141' ]</pre> <h3 id="不同含义的!:断言和范围的组合用法">不同含义的'?!':断言和范围的组合用法</h3> <p>不同含义的<code>?!</code> 结合使用 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Assertions">断言</a> <code>/x(?!y)/ </code>和 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges">范围</a> <code>[^?!]</code>.</p> -<pre class="notranslate">let orangeNotLemon = "Do you want to have an orange? Yes, I do not want to have a lemon!"; +<pre>let orangeNotLemon = "Do you want to have an orange? Yes, I do not want to have a lemon!"; let selectNotLemonRegex = /[^?!]+have(?! a lemon)[^?!]+[?!]/gi console.log(orangeNotLemon.match(selectNotLemonRegex)); // [ 'Do you want to have an orange?' ] @@ -225,7 +225,7 @@ console.log(orangeNotLemon.match(selectNotOrangeRegex)); // [ ' Yes, I do not wa <h3 id="向后断言">向后断言</h3> -<pre class="notranslate">let oranges = ['ripe orange A ', 'green orange B', 'ripe orange C',]; +<pre>let oranges = ['ripe orange A ', 'green orange B', 'ripe orange C',]; let ripe_oranges = oranges.filter( fruit => fruit.match(/(?<=ripe )orange/)); console.log(ripe_oranges); // [ 'ripe orange A ', 'ripe orange C' ]</pre> diff --git a/files/zh-cn/web/javascript/guide/regular_expressions/character_classes/index.html b/files/zh-cn/web/javascript/guide/regular_expressions/character_classes/index.html index 26b1f4ee4a..80f9181f89 100644 --- a/files/zh-cn/web/javascript/guide/regular_expressions/character_classes/index.html +++ b/files/zh-cn/web/javascript/guide/regular_expressions/character_classes/index.html @@ -144,7 +144,7 @@ translation_of: Web/JavaScript/Guide/Regular_Expressions/Character_Classes <h3 id="Looking_for_a_series_of_digits">Looking for a series of digits</h3> -<pre class="brush: js notranslate">var randomData = "015 354 8787 687351 3512 8735"; +<pre class="brush: js">var randomData = "015 354 8787 687351 3512 8735"; var regexpFourDigits = /\b\d{4}\b/g; // \b indicates a boundary (i.e. do not start matching in the middle of a word) // \d{4} indicates a digit, four times @@ -157,7 +157,7 @@ console.table(randomData.match(regexpFourDigits)); <h3 id="Looking_for_a_word_from_the_latin_alphabet_starting_with_A">Looking for a word (from the latin alphabet) starting with A</h3> -<pre class="brush: js notranslate">var aliceExcerpt = "I’m sure I’m not Ada,’ she said, ‘for her hair goes in such long ringlets, and mine doesn’t go in ringlets at all."; +<pre class="brush: js">var aliceExcerpt = "I’m sure I’m not Ada,’ she said, ‘for her hair goes in such long ringlets, and mine doesn’t go in ringlets at all."; var regexpWordStartingWithA = /\b[aA]\w+/g; // \b indicates a boundary (i.e. do not start matching in the middle of a word) // [aA] indicates the letter a or A @@ -171,7 +171,7 @@ console.table(aliceExcerpt.match(regexpWordStartingWithA)); <p>Instead of the Latin alphabet, we can use a range of Unicode characters to identify a word (thus being able to deal with text in other languages like Russian or Arabic). The "Basic Multilingual Plane" of Unicode contains most of the characters used around the world and we can use character classes and ranges to match words written with those characters.</p> -<pre class="brush: js notranslate">var nonEnglishText = "Приключения Алисы в Стране чудес"; +<pre class="brush: js">var nonEnglishText = "Приключения Алисы в Стране чудес"; var regexpBMPWord = /([\u0000-\u0019\u0021-\uFFFF])+/gu; // BMP goes through U+0000 to U+FFFF but space is U+0020 diff --git a/files/zh-cn/web/javascript/guide/regular_expressions/groups_and_ranges/index.html b/files/zh-cn/web/javascript/guide/regular_expressions/groups_and_ranges/index.html index 9a73c9b8ef..8aac5048dc 100644 --- a/files/zh-cn/web/javascript/guide/regular_expressions/groups_and_ranges/index.html +++ b/files/zh-cn/web/javascript/guide/regular_expressions/groups_and_ranges/index.html @@ -94,7 +94,7 @@ translation_of: Web/JavaScript/Guide/Regular_Expressions/Groups_and_Ranges <h3 id="计算元音数">计算元音数</h3> -<pre class="brush: js notranslate">var aliceExcerpt = "There was a long silence after this, and Alice could only hear whispers now and then."; +<pre class="brush: js">var aliceExcerpt = "There was a long silence after this, and Alice could only hear whispers now and then."; var regexpVowels = /[aeiouy]/g; console.log("Number of vowels:", aliceExcerpt.match(regexpVowels).length); @@ -102,7 +102,7 @@ console.log("Number of vowels:", aliceExcerpt.match(regexpVowels).length); <h3 id="使用_组">使用 组</h3> -<pre class="brush: js notranslate">let personList = `First_Name: John, Last_Name: Doe +<pre class="brush: js">let personList = `First_Name: John, Last_Name: Doe First_Name: Jane, Last_Name: Smith`; let regexpNames = /First_Name: (\w+), Last_Name: (\w+)/mg; @@ -114,7 +114,7 @@ do { <h3 id="使用命名组">使用命名组</h3> -<pre class="brush: js notranslate">let users= `姓氏: 李, 名字: 雷 +<pre class="brush: js">let users= `姓氏: 李, 名字: 雷 姓氏: 韩, 名字: 梅梅`; let regexpNames = /姓氏: (?<first>.+), 名字: (?<last>.+)/mg; diff --git a/files/zh-cn/web/javascript/guide/regular_expressions/index.html b/files/zh-cn/web/javascript/guide/regular_expressions/index.html index 4d88167c80..b38f643ced 100644 --- a/files/zh-cn/web/javascript/guide/regular_expressions/index.html +++ b/files/zh-cn/web/javascript/guide/regular_expressions/index.html @@ -21,14 +21,14 @@ translation_of: Web/JavaScript/Guide/Regular_Expressions <p>使用一个正则表达式字面量,其由包含在斜杠之间的模式组成,如下所示:</p> -<pre class="brush: js notranslate">var re = /ab+c/; +<pre class="brush: js">var re = /ab+c/; </pre> <p>脚本加载后,正则表达式字面量就会被编译。当正则表达式保持不变时,使用此方法可获得更好的性能。</p> <p>或者调用<code><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/RegExp" title="zh-CN/docs/JavaScript/Reference/Global Objects/RegExp">RegExp</a></code>对象的构造函数,如下所示:</p> -<pre class="brush: js notranslate">var re = new RegExp("ab+c"); +<pre class="brush: js">var re = new RegExp("ab+c"); </pre> <p>在脚本运行过程中,用构造函数创建的正则表达式会被编译。如果正则表达式将会改变,或者它将会从用户输入等来源中动态地产生,就需要使用构造函数来创建正则表达式。</p> @@ -384,7 +384,7 @@ translation_of: Web/JavaScript/Guide/Regular_Expressions <p>将用户输入转义为正则表达式中的一个字面字符串, 可以通过简单的替换来实现:</p> -<pre class="brush: js notranslate">function escapeRegExp(string) { +<pre class="brush: js">function escapeRegExp(string) { return string.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); //$&表示整个被匹配的字符串 }</pre> @@ -451,13 +451,13 @@ translation_of: Web/JavaScript/Guide/Regular_Expressions <p>在接下来的例子中,脚本将使用exec方法在一个字符串中查找一个匹配。</p> -<pre class="brush: js notranslate">var myRe = /d(b+)d/g; +<pre class="brush: js">var myRe = /d(b+)d/g; var myArray = myRe.exec("cdbbdbsbz"); </pre> <p>如果你不需要访问正则表达式的属性,这个脚本通过另一个方法来创建myArray:</p> -<pre class="brush: js notranslate">var myArray = /d(b+)d/g.exec("cdbbdbsbz"); +<pre class="brush: js">var myArray = /d(b+)d/g.exec("cdbbdbsbz"); // 和 "cdbbdbsbz".match(/d(b+)d/g); 相似。 // 但是 "cdbbdbsbz".match(/d(b+)d/g) 输出数组 [ "dbbd" ], // 而 /d(b+)d/g.exec('cdbbdbsbz') 输出数组 [ "dbbd", "bb", index: 1, input: "cdbbdbsbz" ]. @@ -466,7 +466,7 @@ var myArray = myRe.exec("cdbbdbsbz"); <p>如果你想通过一个字符串构建正则表达式,那么这个脚本还有另一种方法:</p> -<pre class="brush: js notranslate">var myRe = new RegExp("d(b+)d", "g"); +<pre class="brush: js">var myRe = new RegExp("d(b+)d", "g"); var myArray = myRe.exec("cdbbdbsbz"); </pre> @@ -520,25 +520,25 @@ var myArray = myRe.exec("cdbbdbsbz"); <p>如这个例子中的第二种形式所示,你可以使用对象初始器创建一个正则表达式实例,但不分配给变量。如果你这样做,那么,每一次使用时都会创建一个新的正则表达式实例。因此,如果你不把正则表达式实例分配给一个变量,你以后将不能访问这个正则表达式实例的属性。例如,假如你有如下脚本:</p> -<pre class="brush: js notranslate">var myRe = /d(b+)d/g; +<pre class="brush: js">var myRe = /d(b+)d/g; var myArray = myRe.exec("cdbbdbsbz"); console.log("The value of lastIndex is " + myRe.lastIndex); </pre> <p>这个脚本输出如下:</p> -<pre class="notranslate">The value of lastIndex is 5 +<pre>The value of lastIndex is 5 </pre> <p>然而,如果你有如下脚本:</p> -<pre class="brush: js notranslate">var myArray = /d(b+)d/g.exec("cdbbdbsbz"); +<pre class="brush: js">var myArray = /d(b+)d/g.exec("cdbbdbsbz"); console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex); </pre> <p>它显示为:</p> -<pre class="notranslate">The value of lastIndex is 0 +<pre>The value of lastIndex is 0 </pre> <p>当发生/d(b+)d/g使用两个不同状态的正则表达式对象,lastIndex属性会得到不同的值。如果你需要访问一个正则表达式的属性,则需要创建一个对象初始化生成器,你应该首先把它赋值给一个变量。</p> @@ -551,7 +551,7 @@ console.log("The value of lastIndex is " + /d(b+)d/g.lastIndex); <p>下面的脚本使用replace()方法来转换字符串中的单词。在匹配到的替换文本中,脚本使用替代的$ 1,$ 2表示第一个和第二个括号的子字符串匹配。</p> -<pre class="brush: js notranslate">var re = /(\w+)\s(\w+)/; +<pre class="brush: js">var re = /(\w+)\s(\w+)/; var str = "John Smith"; var newstr = str.replace(re, "$2, $1"); console.log(newstr); @@ -601,19 +601,19 @@ console.log(newstr); <p>为了在正则表达式中包含标志,请使用以下语法:</p> -<pre class="brush: js notranslate">var re = /pattern/flags; +<pre class="brush: js">var re = /pattern/flags; </pre> <p>或者</p> -<pre class="brush: js notranslate">var re = new RegExp("pattern", "flags"); +<pre class="brush: js">var re = new RegExp("pattern", "flags"); </pre> <p>值得注意的是,标志是一个正则表达式的一部分,它们在接下来的时间将不能添加或删除。</p> <p>例如,re = /\w+\s/g 将创建一个查找一个或多个字符后有一个空格的正则表达式,或者组合起来像此要求的字符串。</p> -<pre class="brush: js notranslate">var re = /\w+\s/g; +<pre class="brush: js">var re = /\w+\s/g; var str = "fee fi fo fum"; var myArray = str.match(re); console.log(myArray); @@ -623,19 +623,19 @@ console.log(myArray); <p>这段代码将输出 ["fee ", "fi ", "fo "]。在这个例子中,你可以将:</p> -<pre class="brush: js notranslate">var re = /\w+\s/g; +<pre class="brush: js">var re = /\w+\s/g; </pre> <p>替换成:</p> -<pre class="brush: js notranslate">var re = new RegExp("\\w+\\s", "g"); +<pre class="brush: js">var re = new RegExp("\\w+\\s", "g"); </pre> <p>并且能获取到相同的结果。</p> <p>使用<code>.exec()</code>方法时,与'<code>g</code>'标志关联的行为是不同的。 (“class”和“argument”的作用相反:在<code>.match()</code>的情况下,字符串类(或数据类型)拥有该方法,而正则表达式只是一个参数,而在<code>.exec()</code>的情况下,它是拥有该方法的正则表达式,其中字符串是参数。对比<em><code>str.match(re)</code></em>与<em><code>re.exec(str)</code></em> ), '<code>g</code>'标志与<code>.exec()</code>方法一起使用获得迭代进展。</p> -<pre class="brush: js notranslate">var xArray; while(xArray = re.exec(str)) console.log(xArray); +<pre class="brush: js">var xArray; while(xArray = re.exec(str)) console.log(xArray); // produces: // ["fee ", index: 0, input: "fee fi fo fum"] // ["fi ", index: 4, input: "fee fi fo fum"] @@ -651,7 +651,7 @@ console.log(myArray); <p>以下例子解释了正则表达式的构成和 <code>string.split()</code> 以及 <code>string.replace()</code>的用途。它会整理一个只有粗略格式的含有全名(名字首先出现)的输入字符串,这个字符串被空格、换行符和一个分号分隔。最终,它会颠倒名字顺序(姓氏首先出现)和list的类型。</p> -<pre class="brush: js notranslate">// 下面这个姓名字符串包含了多个空格和制表符, +<pre class="brush: js">// 下面这个姓名字符串包含了多个空格和制表符, // 且在姓和名之间可能有多个空格和制表符。 var names = "Orange Trump ;Fred Barney; Helen Rigby ; Bill Abel ; Chris Hand "; @@ -716,7 +716,7 @@ console.log(output.join("\n")); <p>当用户按下 Enter 设置 RegExp.input,这些变化也能被激活。</p> -<pre class="brush: html notranslate"><!DOCTYPE html> +<pre class="brush: html"><!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> diff --git a/files/zh-cn/web/javascript/guide/regular_expressions/quantifiers/index.html b/files/zh-cn/web/javascript/guide/regular_expressions/quantifiers/index.html index d705953a69..1173553f2d 100644 --- a/files/zh-cn/web/javascript/guide/regular_expressions/quantifiers/index.html +++ b/files/zh-cn/web/javascript/guide/regular_expressions/quantifiers/index.html @@ -85,14 +85,14 @@ original_slug: Web/JavaScript/Guide/Regular_Expressions/量词 <h3 id="重复模式">重复模式</h3> -<pre class="brush: js notranslate">var wordEndingWithAs = /\w+a+/; +<pre class="brush: js">var wordEndingWithAs = /\w+a+/; var delicateMessage = "This is Spartaaaaaaa"; console.table(delicateMessage.match(wordEndingWithAs)); // [ "Spartaaaaaaa" ]</pre> <h3 id="计算字符集">计算字符集</h3> -<pre class="brush: js notranslate">var singleLetterWord = /\b\w\b/g; +<pre class="brush: js">var singleLetterWord = /\b\w\b/g; var notSoLongWord = /\b\w{1,6}\b/g; var loooongWord = /\b\w{13,}\b/g; @@ -105,7 +105,7 @@ console.table(sentence.match(loooongWord)); // ["multiplication"]可选可 <h3 id="可选字符"> 可选字符</h3> -<pre class="brush: js notranslate">var britishText = "He asked his neighbour a favour."; +<pre class="brush: js">var britishText = "He asked his neighbour a favour."; var americanText = "He asked his neighbor a favor."; var regexpEnding = /\w+ou?r/g; @@ -123,7 +123,7 @@ console.table(americanText.match(regexpEnding)); <h3 id="贪婪_与_非贪婪的">贪婪 与 非贪婪的</h3> -<pre class="brush: js notranslate">var text = "I must be getting somewhere near the centre of the earth."; +<pre class="brush: js">var text = "I must be getting somewhere near the centre of the earth."; var greedyRegexp = /[\w ]+/; // [\w ] a letter of the latin alphabet or a whitespace // + one or several times diff --git a/files/zh-cn/web/javascript/guide/regular_expressions/unicode_property_escapes/index.html b/files/zh-cn/web/javascript/guide/regular_expressions/unicode_property_escapes/index.html index db7312bea4..973820343c 100644 --- a/files/zh-cn/web/javascript/guide/regular_expressions/unicode_property_escapes/index.html +++ b/files/zh-cn/web/javascript/guide/regular_expressions/unicode_property_escapes/index.html @@ -21,7 +21,7 @@ translation_of: Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escape <div class="hidden">The following section is also duplicated on <a href="/en-US/docs/Web/JavaScript/Guide/Regular_Expressions/Cheatsheet">this cheatsheet</a>. Do not forget to edit it as well, thanks!</div> -<pre class="brush: js notranslate">// Non-binary 属性 +<pre class="brush: js">// Non-binary 属性 \p{<em>Unicode属性值</em>} \p{<em>Unicode属性名</em>=<em>Unicode属性值</em>} @@ -66,7 +66,7 @@ translation_of: Web/JavaScript/Guide/Regular_Expressions/Unicode_Property_Escape <p>它们可匹配字母、数字、符号、标点符号、空格等等。一般类别详见 <a href="https://unicode.org/reports/tr18/#General_Category_Property">the Unicode specification</a>.</p> -<pre class="brush: js notranslate">// finding all the letters of a text +<pre class="brush: js">// finding all the letters of a text let story = "It’s the Cheshire Cat: now I shall have somebody to talk to."; // Most explicit form @@ -88,7 +88,7 @@ story.match(/\p{Lu}|\p{Ll}|\p{Lt}|\p{Lm}|\p{Lo}/gu); <p>比如,<code>A</code> 属于 <code>拉丁文</code>,<code>ε</code> 属于<code>希腊(Greek)</code>文。</p> -<pre class="brush: js notranslate">let mixedCharacters = "aεЛ"; +<pre class="brush: js">let mixedCharacters = "aεЛ"; // Using the canonical "long" name of the script mixedCharacters.match(/\p{Script=Latin}/u); // a @@ -104,7 +104,7 @@ mixedCharacters.match(/\p{Sc=Cyrillic}/u); // Л <p>某字符用于多种文字时,<code>Script</code> 优先匹配最主要使用那个字符的文字。如果想要根据非主要的文字进行匹配,我们可以使用 <code>Script_Extensions</code> 属性 (简写为<code>Scx</code>).</p> -<pre class="brush: js notranslate">// ٢ is the digit 2 in Arabic-Indic notation +<pre class="brush: js">// ٢ is the digit 2 in Arabic-Indic notation // while it is predominantly written within the Arabic script // it can also be written in the Thaana script @@ -121,7 +121,7 @@ mixedCharacters.match(/\p{Sc=Cyrillic}/u); // Л <p>Unicode 属性转义 categories 包含更多字符, <code>\p{Letter}</code> 或 <code>\p{Number}</code> 将会适用于任何文字。</p> -<pre class="brush: js notranslate">// Trying to use ranges to avoid \w limitations: +<pre class="brush: js">// Trying to use ranges to avoid \w limitations: const nonEnglishText = "Приключения Алисы в Стране чудес"; const regexpBMPWord = /([\u0000-\u0019\u0021-\uFFFF])+/gu; diff --git a/files/zh-cn/web/javascript/guide/text_formatting/index.html b/files/zh-cn/web/javascript/guide/text_formatting/index.html index fbe34d2cd6..b0f8b412fe 100644 --- a/files/zh-cn/web/javascript/guide/text_formatting/index.html +++ b/files/zh-cn/web/javascript/guide/text_formatting/index.html @@ -18,7 +18,7 @@ translation_of: Web/JavaScript/Guide/Text_formatting <p>可以使用单引号或双引号创建简单的字符串:</p> -<pre class="brush: js notranslate">'foo' +<pre class="brush: js">'foo' "bar"</pre> <p>可以使用转义序列来创建更复杂的字符串:</p> @@ -27,14 +27,14 @@ translation_of: Web/JavaScript/Guide/Text_formatting <p>\x之后的数值将被认为是一个16进制数.</p> -<pre class="brush: js notranslate">'\xA9' // "©" +<pre class="brush: js">'\xA9' // "©" </pre> <h4 id="Unicode转义序列">Unicode转义序列</h4> <p>Unicode转义序列在\u之后需要至少4个字符.</p> -<pre class="brush: js notranslate">'\u00A9' // "©"</pre> +<pre class="brush: js">'\u00A9' // "©"</pre> <h4 id="Unicode字元逸出">Unicode字元逸出</h4> @@ -42,7 +42,7 @@ translation_of: Web/JavaScript/Guide/Text_formatting <p>请参阅 {{jsxref("String.fromCodePoint()")}} 或 {{jsxref("String.prototype.codePointAt()")}}。</p> -<pre class="brush: js notranslate">'\u{2F804}' +<pre class="brush: js">'\u{2F804}' // the same with simple Unicode escapes '\uD87E\uDC04'</pre> @@ -51,7 +51,7 @@ translation_of: Web/JavaScript/Guide/Text_formatting <p>{{jsxref("String")}} 对象是对原始string类型的封装 .</p> -<pre class="brush: js notranslate">const foo = new String('foo'); // 创建一个 String 对象 +<pre class="brush: js">const foo = new String('foo'); // 创建一个 String 对象 console.log(foo); // 输出: [String: 'foo'] typeof foo; // 返回 'object'</pre> @@ -59,14 +59,14 @@ typeof foo; // 返回 'object'</pre> <p>除非必要, 应该尽量使用 String 字面值,因为String对象的某些行为可能并不与直觉一致。举例:</p> -<pre class="brush: js notranslate">const firstString = '2 + 2'; //创建一个字符串字面量 +<pre class="brush: js">const firstString = '2 + 2'; //创建一个字符串字面量 const secondString = new String('2 + 2'); // 创建一个字符串对象 eval(firstString); // 返回数字 4 eval(secondString); // 返回包含 "2 + 2" 的字符串对象</pre> <p><code>String</code> 对象有一个属性 <code>length</code>,标识了字符串中 UTF-16 的码点个数。举例,下面的代码把 13 赋值给了<code>helloLength</code>,因为 "Hello, World!" 包含 13 个字符,每个字符用一个 UTF-16 码点表示。你可以通过数组的方式访问每一个码点,但你不能修改每个字符,因为字符串是不变的类数组对象: </p> -<pre class="brush: js notranslate">const hello = 'Hello, World!'; +<pre class="brush: js">const hello = 'Hello, World!'; const helloLength = hello.length; hello[0] = 'L'; // 无效,因为字符串是不变的 hello[0]; // 返回 "H"</pre> @@ -155,14 +155,14 @@ hello[0]; // 返回 "H"</pre> <p>源代码中插入的任何新行开始字符都作为模板字符串的内容. 使用一般的字符串时, 为了创建多行的字符串不得不用如下语法:</p> -<pre class="brush: js notranslate">console.log("string text line 1\n\ +<pre class="brush: js">console.log("string text line 1\n\ string text line 2"); // "string text line 1 // string text line 2"</pre> <p>为了实现同样效果的多行字符串, 现在可以写成如下形式:</p> -<pre class="brush: js notranslate">console.log(`string text line 1 +<pre class="brush: js">console.log(`string text line 1 string text line 2`); // "string text line 1 // string text line 2"</pre> @@ -171,14 +171,14 @@ string text line 2`); <p>为了在一般的字符串中嵌入表达式, 需要使用如下语法:</p> -<pre class="brush: js notranslate">const five = 5; +<pre class="brush: js">const five = 5; const ten = 10; console.log('Fifteen is ' + (five + ten) + ' and not ' + (2 * five + ten) + '.'); // "Fifteen is 15 and not 20."</pre> <p>现在, 使用模板字符串, 可以使用语法糖让类似功能的实现代码更具可读性:</p> -<pre class="brush: js notranslate">const five = 5; +<pre class="brush: js">const five = 5; const ten = 10; console.log(`Fifteen is ${five + ten} and not ${2 * five + ten}.`); // "Fifteen is 15 and not 20."</pre> @@ -193,7 +193,7 @@ console.log(`Fifteen is ${five + ten} and not ${2 * five + ten}.`); <p>{{jsxref("DateTimeFormat")}} 对象在日期和时间的格式化方面很有用. 下面的代码把一个日期格式化为美式英语格式. (不同时区结果不同.)</p> -<pre class="brush: js notranslate">const msPerDay = 24 * 60 * 60 * 1000; +<pre class="brush: js">const msPerDay = 24 * 60 * 60 * 1000; // July 17, 2014 00:00:00 UTC. const july172014 = new Date(msPerDay * (44 * 365 + 11 + 197));//2014-1970=44年 @@ -211,7 +211,7 @@ console.log(americanDateTime(july172014)); // 07/16/14, 5:00 PM PDT <p>{{jsxref("NumberFormat")}} 对象在数字的格式化方面很有用, 比如货币数量值.</p> -<pre class="brush: js notranslate">var gasPrice = new Intl.NumberFormat("en-US", +<pre class="brush: js">var gasPrice = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD", minimumFractionDigits: 3 }); @@ -229,7 +229,7 @@ console.log(hanDecimalRMBInChina.format(1314.25)); // ¥ 一,三一四.二五 <p>举例, 德语中<em>有两种不同的排序方式 电话本(phonebook)</em> 和 字典(<em>dictionary)</em>. 电话本排序强调发音, 比如在排序前 “ä”, “ö”等被扩展为 “ae”, “oe”等发音.</p> -<pre class="brush: js notranslate">var names = ["Hochberg", "Hönigswald", "Holzman"]; +<pre class="brush: js">var names = ["Hochberg", "Hönigswald", "Holzman"]; var germanPhonebook = new Intl.Collator("de-DE-u-co-phonebk"); @@ -240,7 +240,7 @@ console.log(names.sort(germanPhonebook.compare).join(", ")); <p>有些德语词包含变音, 所以在字典中忽略变音进行排序是合理的 (除非待排序的单词只有变音部分不同: <em>schon</em> 先于 <em>schön</em>).</p> -<pre class="brush: js notranslate">var germanDictionary = new Intl.Collator("de-DE-u-co-dict"); +<pre class="brush: js">var germanDictionary = new Intl.Collator("de-DE-u-co-dict"); // as if sorting ["Hochberg", "Honigswald", "Holzman"]: console.log(names.sort(germanDictionary.compare).join(", ")); diff --git a/files/zh-cn/web/javascript/guide/using_promises/index.html b/files/zh-cn/web/javascript/guide/using_promises/index.html index c714260d7f..22a0163216 100644 --- a/files/zh-cn/web/javascript/guide/using_promises/index.html +++ b/files/zh-cn/web/javascript/guide/using_promises/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Guide/Using_promises <p>以下为使用 <code>createAudioFileAsync()</code> 的示例:</p> -<pre class="brush: js notranslate">// 成功的回调函数 +<pre class="brush: js">// 成功的回调函数 function successCallback(result) { console.log("音频文件创建成功: " + result); } @@ -36,13 +36,13 @@ createAudioFileAsync(audioSettings, successCallback, failureCallback)</pre> <p>如果函数 <code>createAudioFileAsync()</code> 被重写为返回 Promise 的形式,那么我们可以像下面这样简单地调用它:</p> -<pre class="brush: js line-numbers language-js notranslate">const promise = createAudioFileAsync(audioSettings); +<pre class="brush: js line-numbers language-js">const promise = createAudioFileAsync(audioSettings); promise.then(successCallback, failureCallback); </pre> <p>或者简写为:</p> -<pre class="brush: js line-numbers language-js notranslate">createAudioFileAsync(audioSettings).then(successCallback, failureCallback); +<pre class="brush: js line-numbers language-js">createAudioFileAsync(audioSettings).then(successCallback, failureCallback); </pre> <p>我们把这个称为 <em>异步函数调用</em>,这种形式有若干优点,下面我们将会逐一讨论。</p> @@ -65,13 +65,13 @@ promise.then(successCallback, failureCallback); <p>见证奇迹的时刻:<code>then()</code> 函数会返回一个和原来不同的<strong>新的 Promise</strong>:</p> -<pre class="brush: js line-numbers language-js notranslate">const promise = doSomething(); +<pre class="brush: js line-numbers language-js">const promise = doSomething(); const promise2 = promise.then(successCallback, failureCallback); </pre> <p>或者</p> -<pre class="brush: js notranslate">const promise2 = doSomething().then(successCallback, failureCallback);</pre> +<pre class="brush: js">const promise2 = doSomething().then(successCallback, failureCallback);</pre> <p><code>promise2</code> 不仅表示 <code>doSomething()</code> 函数的完成,也代表了你传入的 <code>successCallback</code> 或者 <code>failureCallback</code> 的完成,这两个函数也可以返回一个 Promise 对象,从而形成另一个异步操作,这样的话,在 <code>promise2</code> 上新增的回调函数会排在这个 Promise 对象的后面。</p> @@ -79,7 +79,7 @@ const promise2 = promise.then(successCallback, failureCallback); <p>在过去,要想做多重的异步操作,会导致经典的回调地狱:</p> -<pre class="brush: js notranslate">doSomething(function(result) { +<pre class="brush: js">doSomething(function(result) { doSomethingElse(result, function(newResult) { doThirdThing(newResult, function(finalResult) { console.log('Got the final result: ' + finalResult); @@ -90,7 +90,7 @@ const promise2 = promise.then(successCallback, failureCallback); <p>现在,我们可以把回调绑定到返回的 Promise 上,形成一个 Promise 链:</p> -<pre class="brush: js notranslate">doSomething().then(function(result) { +<pre class="brush: js">doSomething().then(function(result) { return doSomethingElse(result); }) .then(function(newResult) { @@ -104,7 +104,7 @@ const promise2 = promise.then(successCallback, failureCallback); <p>then 里的参数是可选的,<code>catch(failureCallback)</code> 是 <code>then(null, failureCallback)</code> 的缩略形式。如下所示,我们也可以用<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions">箭头函数</a>来表示:</p> -<pre class="brush: js notranslate">doSomething() +<pre class="brush: js">doSomething() .then(result => doSomethingElse(result)) .then(newResult => doThirdThing(newResult)) .then(finalResult => { @@ -119,7 +119,7 @@ const promise2 = promise.then(successCallback, failureCallback); <p>有可能会在一个回调失败之后继续使用链式操作,即,使用一个 <code>catch</code>,这对于在链式操作中抛出一个失败之后,再次进行新的操作会很有用。请阅读下面的例子:</p> -<pre class="brush: js notranslate">new Promise((resolve, reject) => { +<pre class="brush: js">new Promise((resolve, reject) => { console.log('初始化'); resolve(); @@ -139,7 +139,7 @@ const promise2 = promise.then(successCallback, failureCallback); <p>输出结果如下:</p> -<pre class="notranslate">初始化 +<pre>初始化 执行“那个” 执行“这个”,无论前面发生了什么 </pre> @@ -150,7 +150,7 @@ const promise2 = promise.then(successCallback, failureCallback); <p>在之前的回调地狱示例中,你可能记得有 3 次 <code>failureCallback</code> 的调用,而在 Promise 链中只有尾部的一次调用。</p> -<pre class="brush: js notranslate">doSomething() +<pre class="brush: js">doSomething() .then(result => doSomethingElse(result)) .then(newResult => doThirdThing(newResult)) .then(finalResult => console.log(`Got the final result: ${finalResult}`)) @@ -160,7 +160,7 @@ const promise2 = promise.then(successCallback, failureCallback); <p>通常,一遇到异常抛出,浏览器就会顺着 Promise 链寻找下一个 <code>onRejected</code> 失败回调函数或者由 <code>.catch()</code> 指定的回调函数。这和以下同步代码的工作原理(执行过程)非常相似。</p> -<pre class="brush: js notranslate">try { +<pre class="brush: js">try { let result = syncDoSomething(); let newResult = syncDoSomethingElse(result); let finalResult = syncDoThirdThing(newResult); @@ -172,7 +172,7 @@ const promise2 = promise.then(successCallback, failureCallback); <p>在 ECMAScript 2017 标准的 <code><a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/async_function">async/await</a></code> 语法糖中,这种异步代码的对称性得到了极致的体现:</p> -<pre class="brush: js notranslate">async function foo() { +<pre class="brush: js">async function foo() { try { const result = await doSomething(); const newResult = await doSomethingElse(result); @@ -204,7 +204,7 @@ const promise2 = promise.then(successCallback, failureCallback); <p>一个特别有用的例子:当你使用 {{Glossary("Node.js")}} 时,有些依赖模块可能会有未被处理的 rejected promises,这些都会在运行时打印到控制台。你可以在自己的代码中捕捉这些信息,然后添加与 {{domxref("Window.unhandledrejection_event", "unhandledrejection")}} 相应的处理函数来做分析和处理,或只是为了让你的输出更整洁。举例如下:</p> -<pre class="brush: js notranslate">window.addEventListener("unhandledrejection", event => { +<pre class="brush: js">window.addEventListener("unhandledrejection", event => { /* 你可以在这里添加一些代码,以便检查 event.promise 中的 promise 和 event.reason 中的 rejection 原因 */ @@ -223,14 +223,14 @@ const promise2 = promise.then(successCallback, failureCallback); <p>理想状态下,所有的异步函数都已经返回 Promise 了。但有一些 API 仍然使用旧方式来传入的成功(或者失败)的回调。典型的例子就是 {{domxref("WindowTimers.setTimeout", "setTimeout()")}} 函数:</p> -<pre class="brush: js notranslate">setTimeout(() => saySomething("10 seconds passed"), 10000); +<pre class="brush: js">setTimeout(() => saySomething("10 seconds passed"), 10000); </pre> <p>混用旧式回调和 Promise 可能会造成运行时序问题。如果 <code>saySomething</code> 函数失败了,或者包含了编程错误,那就没有办法捕获它了。这得怪 <code>setTimeout</code>。</p> <p>幸运地是,我们可以用 Promise 来封装它。最好的做法是,将这些有问题的函数封装起来,留在底层,并且永远不要再直接调用它们:</p> -<pre class="brush: js notranslate">const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); +<pre class="brush: js">const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback); </pre> @@ -245,33 +245,33 @@ wait(10000).then(() => saySomething("10 seconds")).catch(failureCallback); <p>我们可以发起并行操作,然后等多个操作全部结束后进行下一步操作,如下:</p> -<pre class="brush: js notranslate">Promise.all([func1(), func2(), func3()]) +<pre class="brush: js">Promise.all([func1(), func2(), func3()]) .then(([result1, result2, result3]) => { /* use result1, result2 and result3 */ });</pre> <p>可以使用一些聪明的 JavaScript 写法实现时序组合:</p> -<pre class="brush: js notranslate">[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve()) +<pre class="brush: js">[func1, func2, func3].reduce((p, f) => p.then(f), Promise.resolve()) .then(result3 => { /* use result3 */ });</pre> <p>通常,我们递归调用一个由异步函数组成的数组时,相当于一个 Promise 链:</p> -<pre class="notranslate"><code>Promise.resolve().then(func1).then(func2).then(func3);</code></pre> +<pre><code>Promise.resolve().then(func1).then(func2).then(func3);</code></pre> <p>我们也可以写成可复用的函数形式,这在函数式编程中极为普遍:</p> -<pre class="brush: js notranslate">const applyAsync = (acc,val) => acc.then(val); +<pre class="brush: js">const applyAsync = (acc,val) => acc.then(val); const composeAsync = (...funcs) => x => funcs.reduce(applyAsync, Promise.resolve(x)); </pre> <p><code>composeAsync()</code> 函数将会接受任意数量的函数作为其参数,并返回一个新的函数,该函数接受一个通过 composition pipeline 传入的初始值。这对我们来说非常有益,因为任一函数可以是异步或同步的,它们能被保证按顺序执行:</p> -<pre class="brush: js notranslate">const transformData = composeAsync(func1, func2, func3); +<pre class="brush: js">const transformData = composeAsync(func1, func2, func3); const result3 = transformData(data); </pre> <p>在 ECMAScript 2017 标准中, 时序组合可以通过使用 <code>async/await</code> 而变得更简单:</p> -<pre class="brush: js notranslate">let result; +<pre class="brush: js">let result; for (const f of [func1, func2, func3]) { result = await f(result); } @@ -281,13 +281,13 @@ for (const f of [func1, func2, func3]) { <p>为了避免意外,即使是一个已经变成 resolve 状态的 Promise,传递给 <code><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Promise/then">then()</a></code> 的函数也总是会被异步调用:</p> -<pre class="brush: js notranslate">Promise.resolve().then(() => console.log(2)); +<pre class="brush: js">Promise.resolve().then(() => console.log(2)); console.log(1); // 1, 2 </pre> <p>传递到 <code>then()</code> 中的函数被置入到一个微任务队列中,而不是立即执行,这意味着它是在 JavaScript 事件队列的所有运行时结束了,且事件队列被清空之后,才开始执行:</p> -<pre class="brush: js notranslate">const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); +<pre class="brush: js">const wait = ms => new Promise(resolve => setTimeout(resolve, ms)); wait().then(() => console.log(4)); Promise.resolve().then(() => console.log(2)).then(() => console.log(3)); @@ -299,7 +299,7 @@ console.log(1); // 1, 2, 3, 4</pre> <p>嵌套 Promise 是一种可以限制 <code>catch</code> 语句的作用域的控制结构写法。明确来说,嵌套的 <code>catch</code> 仅捕捉在其之前同时还必须是其作用域的 failureres,而捕捉不到在其链式以外或者其嵌套域以外的 error。如果使用正确,那么可以实现高精度的错误修复。</p> -<pre class="brush: js notranslate">doSomethingCritical() +<pre class="brush: js">doSomethingCritical() .then(result => doSomethingOptional() .then(optionalResult => doSomethingExtraNice(optionalResult)) .catch(e => {console.log(e.message)})) // 即使有异常也会忽略,继续运行;(最后会输出) @@ -314,7 +314,7 @@ console.log(1); // 1, 2, 3, 4</pre> <p>在编写 Promise 链时,需要注意以下示例中展示的几个错误:</p> -<pre class="brush: js example-bad notranslate">// 错误示例,包含 3 个问题! +<pre class="brush: js example-bad">// 错误示例,包含 3 个问题! doSomething().then(function(result) { doSomethingElse(result) // 没有返回 Promise 以及没有必要的嵌套 Promise @@ -330,7 +330,7 @@ doSomething().then(function(result) { <p>一个好的经验法则是总是返回或终止 Promise 链,并且一旦你得到一个新的 Promise,返回它。下面是修改后的平面化的代码:</p> -<pre class="brush: js example-good notranslate">doSomething() +<pre class="brush: js example-good">doSomething() .then(function(result) { return doSomethingElse(result); }) diff --git a/files/zh-cn/web/javascript/inheritance_and_the_prototype_chain/index.html b/files/zh-cn/web/javascript/inheritance_and_the_prototype_chain/index.html index b83c68af65..57f9c2bf2a 100644 --- a/files/zh-cn/web/javascript/inheritance_and_the_prototype_chain/index.html +++ b/files/zh-cn/web/javascript/inheritance_and_the_prototype_chain/index.html @@ -39,7 +39,7 @@ translation_of: Web/JavaScript/Inheritance_and_the_prototype_chain <p>这里演示当尝试访问属性时会发生什么:</p> -<pre class="brush: js notranslate">// 让我们从一个函数里创建一个对象o,它自身拥有属性a和b的: +<pre class="brush: js">// 让我们从一个函数里创建一个对象o,它自身拥有属性a和b的: let f = function () { this.a = 1; this.b = 2; @@ -96,7 +96,7 @@ console.log(o.d); // undefined <p>当继承的函数被调用时,<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/this">this</a> 指向的是当前继承的对象,而不是继承的函数所在的原型对象。</p> -<pre class="brush: js notranslate">var o = { +<pre class="brush: js">var o = { a: 2, m: function(){ return this.a + 1; @@ -121,7 +121,7 @@ console.log(p.m()); // 5 <p>正如之前提到的,在 JavaScript 中,函数(function)是允许拥有属性的。所有的函数会有一个特别的属性 —— <code>prototype</code> 。请注意,以下的代码是独立的(出于严谨,假定页面没有其他的JavaScript代码)。为了最佳的学习体验,我们强烈建议阁下打开浏览器的控制台(在Chrome和火狐浏览器中,按Ctrl+Shift+I即可),进入“console”选项卡,然后把如下的JavaScript代码复制粘贴到窗口中,最后通过按下回车键运行代码。</p> -<pre class="brush: js notranslate">function doSomething(){} +<pre class="brush: js">function doSomething(){} console.log( doSomething.prototype ); // 和声明函数的方式无关, // JavaScript 中的函数永远有一个默认原型属性。 @@ -130,7 +130,7 @@ console.log( doSomething.prototype );</pre> <p>在控制台显示的JavaScript代码块中,我们可以看到doSomething函数的一个默认属性prototype。而这段代码运行之后,控制台应该显示类似如下的结果:</p> -<pre class="brush: js notranslate">{ +<pre class="brush: js">{ constructor: ƒ doSomething(), __proto__: { constructor: ƒ Object(), @@ -145,13 +145,13 @@ console.log( doSomething.prototype );</pre> <p>我们可以给doSomething函数的原型对象添加新属性,如下:</p> -<pre class="brush: js notranslate">function doSomething(){} +<pre class="brush: js">function doSomething(){} doSomething.prototype.foo = "bar"; console.log( doSomething.prototype );</pre> <p>可以看到运行后的结果如下:</p> -<pre class="brush: js notranslate">{ +<pre class="brush: js">{ foo: "bar", constructor: ƒ doSomething(), __proto__: { @@ -169,7 +169,7 @@ console.log( doSomething.prototype );</pre> <p>请尝试运行以下代码:</p> -<pre class="brush: js notranslate">function doSomething(){} +<pre class="brush: js">function doSomething(){} doSomething.prototype.foo = "bar"; // add a property onto the prototype var doSomeInstancing = new doSomething(); doSomeInstancing.prop = "some value"; // add a property onto the object @@ -177,7 +177,7 @@ console.log( doSomeInstancing );</pre> <p>运行的结果类似于以下的语句。</p> -<pre class="brush: js notranslate">{ +<pre class="brush: js">{ prop: "some value", __proto__: { foo: "bar", @@ -204,7 +204,7 @@ console.log( doSomeInstancing );</pre> <p>让我们在控制台窗口中输入更多的代码,如下:</p> -<pre class="brush: js notranslate">function doSomething(){} +<pre class="brush: js">function doSomething(){} doSomething.prototype.foo = "bar"; var doSomeInstancing = new doSomething(); doSomeInstancing.prop = "some value"; @@ -217,7 +217,7 @@ console.log("doSomething.prototype.foo: " + doSomething.prototype.foo);</pre> <p>结果如下:</p> -<pre class="brush: js notranslate">doSomeInstancing.prop: some value +<pre class="brush: js">doSomeInstancing.prop: some value doSomeInstancing.foo: bar doSomething.prop: undefined doSomething.foo: undefined @@ -228,7 +228,7 @@ doSomething.prototype.foo: bar</pre> <h3 id="使用语法结构创建的对象">使用语法结构创建的对象</h3> -<pre class="brush: js notranslate">var o = {a: 1}; +<pre class="brush: js">var o = {a: 1}; // o 这个对象继承了 Object.prototype 上面的所有属性 // o 自身没有名为 hasOwnProperty 的属性 @@ -258,7 +258,7 @@ function f(){ <p>在 JavaScript 中,构造器其实就是一个普通的函数。当使用 <a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/new">new 操作符</a> 来作用这个函数时,它就可以被称为构造方法(构造函数)。</p> -<pre class="brush: js notranslate">function Graph() { +<pre class="brush: js">function Graph() { this.vertices = []; this.edges = []; } @@ -277,7 +277,7 @@ var g = new Graph(); <p>ECMAScript 5 中引入了一个新方法:{{jsxref("Object.create()")}}。可以调用这个方法来创建一个新对象。新对象的原型就是调用 create 方法时传入的第一个参数:</p> -<pre class="brush: js notranslate">var a = {a: 1}; +<pre class="brush: js">var a = {a: 1}; // a ---> Object.prototype ---> null var b = Object.create(a); @@ -295,7 +295,7 @@ console.log(d.hasOwnProperty); // undefined, 因为d没有继承Object.prototype <p>ECMAScript6 引入了一套新的关键字用来实现 <a href="/zh-CN/docs/Web/JavaScript/Reference/Classes">class</a>。使用基于类语言的开发人员会对这些结构感到熟悉,但它们是不同的。JavaScript 仍然基于原型。这些新的关键字包括 {{jsxref("Statements/class", "class")}}, {{jsxref("Classes/constructor", "constructor")}},{{jsxref("Classes/static", "static")}},{{jsxref("Classes/extends", "extends")}} 和 {{jsxref("Operators/super", "super")}}。</p> -<pre class="brush: js notranslate">"use strict"; +<pre class="brush: js">"use strict"; class Polygon { constructor(height, width) { @@ -325,7 +325,7 @@ var square = new Square(2);</pre> <p>遍历对象的属性时,原型链上的<strong>每个</strong>可枚举属性都会被枚举出来。要检查对象是否具有自己定义的属性,而不是其原型链上的某个属性,则必须使用所有对象从 <code>Object.prototype</code> 继承的 <code><a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/Object/hasOwnProperty">hasOwnProperty</a></code> 方法。下面给出一个具体的例子来说明它:</p> -<pre class="brush: js notranslate">console.log(g.hasOwnProperty('vertices')); +<pre class="brush: js">console.log(g.hasOwnProperty('vertices')); // true console.log(g.hasOwnProperty('nope')); @@ -365,7 +365,7 @@ console.log(g.__proto__.hasOwnProperty('addVertex')); <tr> <td>New-initialization</td> <td style="vertical-align: top;"> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function foo(){} foo.prototype = { foo_prop: "foo val" @@ -384,7 +384,7 @@ console.log(inst.bar_prop);</pre> <tr> <td>Object.create</td> <td style="vertical-align: top;"> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function foo(){} foo.prototype = { foo_prop: "foo val" @@ -400,7 +400,7 @@ console.log(inst.foo_prop); console.log(inst.bar_prop); </pre> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function foo(){} foo.prototype = { foo_prop: "foo val" @@ -427,7 +427,7 @@ console.log(inst.bar_prop)</pre> <p>Object.setPrototypeOf</p> </td> <td style="vertical-align: top;"> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function foo(){} foo.prototype = { foo_prop: "foo val" @@ -445,7 +445,7 @@ console.log(inst.foo_prop); console.log(inst.bar_prop); </pre> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function foo(){} foo.prototype = { foo_prop: "foo val" @@ -467,7 +467,7 @@ console.log(inst.bar_prop)</pre> <tr> <td>__proto__</td> <td style="vertical-align: top;"> - <pre class="brush: js notranslate"> + <pre class="brush: js"> function foo(){} foo.prototype = { foo_prop: "foo val" @@ -483,7 +483,7 @@ console.log(inst.foo_prop); console.log(inst.bar_prop); </pre> - <pre class="brush: js notranslate"> + <pre class="brush: js"> var inst = { __proto__: { bar_prop: "bar val", @@ -517,17 +517,17 @@ console.log(inst.bar_prop)</pre> <p>因此,当你执行:</p> -<pre class="brush: js notranslate">var o = new Foo();</pre> +<pre class="brush: js">var o = new Foo();</pre> <p>JavaScript 实际上执行的是:</p> -<pre class="brush: js notranslate">var o = new Object(); +<pre class="brush: js">var o = new Object(); o.__proto__ = Foo.prototype; Foo.call(o);</pre> <p>(或者类似上面这样的),然后,当你执行:</p> -<pre class="brush: js notranslate">o.someProp;</pre> +<pre class="brush: js">o.someProp;</pre> <p>它检查 o 是否具有 <code>someProp</code> 属性。如果没有,它会查找 <code>Object.getPrototypeOf(o).someProp</code>,如果仍旧没有,它会继续查找 <code>Object.getPrototypeOf(Object.getPrototypeOf(o)).someProp</code>。</p> @@ -543,7 +543,7 @@ Foo.call(o);</pre> <p><code>B</code> 继承自 <code>A</code>:</p> -<pre class="brush: js notranslate">function A(a){ +<pre class="brush: js">function A(a){ this.varA = a; } diff --git a/files/zh-cn/web/javascript/reference/classes/index.html b/files/zh-cn/web/javascript/reference/classes/index.html index 3b0c5f408f..55bc4d0937 100644 --- a/files/zh-cn/web/javascript/reference/classes/index.html +++ b/files/zh-cn/web/javascript/reference/classes/index.html @@ -26,7 +26,7 @@ translation_of: Web/JavaScript/Reference/Classes <p>定义类的一种方法是使用<strong>类声明</strong>。要声明一个类,你可以使用带有<code>class</code>关键字的类名(这里是“Rectangle”)。</p> -<pre class="brush: js notranslate">class Rectangle { +<pre class="brush: js">class Rectangle { constructor(height, width) { this.height = height; this.width = width; @@ -37,7 +37,7 @@ translation_of: Web/JavaScript/Reference/Classes <p><strong>函数声明</strong>和<strong>类声明</strong>之间的一个重要区别在于, 函数声明会{{Glossary("Hoisting", "提升")}},类声明不会。你首先需要声明你的类,然后再访问它,否则类似以下的代码将抛出{{jsxref("ReferenceError")}}:</p> -<pre class="brush: js example-bad notranslate">let p = new Rectangle(); // ReferenceError +<pre class="brush: js example-bad">let p = new Rectangle(); // ReferenceError class Rectangle {} </pre> @@ -46,7 +46,7 @@ class Rectangle {} <p><strong>类表达式</strong>是定义类的另一种方法。类表达式可以命名或不命名。命名类表达式的名称是该类体的局部名称。(不过,可以通过类的(而不是一个实例的) {{jsxref("Function.name", "name")}} 属性来检索它)。</p> -<pre class="brush: js notranslate">// 未命名/匿名类 +<pre class="brush: js">// 未命名/匿名类 let Rectangle = class { constructor(height, width) { this.height = height; @@ -88,7 +88,7 @@ console.log(Rectangle.name); <p>参见<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Method_definitions">方法定义</a>。</p> -<pre class="brush: js notranslate">class Rectangle { +<pre class="brush: js">class Rectangle { // constructor constructor(height, width) { this.height = height; @@ -113,7 +113,7 @@ console.log(square.area); <p><code><a href="/zh-CN/docs/Web/JavaScript/Reference/Classes/static">static</a></code> 关键字用来定义一个类的一个静态方法。调用静态方法不需要<a href="/zh-CN/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript#The_object_(class_instance)">实例化</a>该类,但不能通过一个类实例调用静态方法。静态方法通常用于为一个应用程序创建工具函数。</p> -<pre class="brush: js notranslate">class Point { +<pre class="brush: js">class Point { constructor(x, y) { this.x = x; this.y = y; @@ -145,7 +145,7 @@ console.log(Point.distance(p1, p2)); <p>当调用静态或原型方法时没有指定 <em>this </em>的值,那么方法内的 <em>this </em>值将被置为 <strong><code>undefined</code></strong>。即使你未设置 <code>"use strict"</code> ,因为 <code>class</code> 体内部的代码总是在严格模式下执行。</p> -<pre class="brush: js notranslate">class Animal { +<pre class="brush: js">class Animal { speak() { return this; } @@ -167,7 +167,7 @@ eat(); // undefined</pre> <p>严格模式下不会发生自动装箱,<em>this </em>值将保留传入状态。</p> -<pre class="brush: js notranslate">function Animal() { } +<pre class="brush: js">function Animal() { } Animal.prototype.speak = function() { return this; @@ -189,7 +189,7 @@ eat(); // global object <p>实例的属性必须定义在类的方法里:</p> -<pre class="notranslate"><code>class Rectangle { +<pre><code>class Rectangle { constructor(height, width) { this.height = height; this.width = width; @@ -199,7 +199,7 @@ eat(); // global object <p>静态的或原型的数据属性必须定义在类定义的外面。</p> -<pre class="notranslate"><code>Rectangle.staticWidth = 20; +<pre><code>Rectangle.staticWidth = 20; Rectangle.prototype.prototypeWidth = 25;</code> </pre> @@ -213,7 +213,7 @@ Rectangle.prototype.prototypeWidth = 25;</code> <p>使用JavaScript字段声明语法,上面的示例可以写成:</p> -<pre class="notranslate"><code>class Rectangle { +<pre><code>class Rectangle { height = 0; width; constructor(height, width) { @@ -231,7 +231,7 @@ Rectangle.prototype.prototypeWidth = 25;</code> <p>使用私有字段,可以按以下方式细化定义。</p> -<pre class="notranslate"><code>class Rectangle { +<pre><code>class Rectangle { #height = 0; #width; constructor(height, width) { @@ -255,7 +255,7 @@ Rectangle.prototype.prototypeWidth = 25;</code> <p><code><a href="/zh-CN/docs/Web/JavaScript/Reference/Classes/extends">extends</a></code> 关键字在 <em>类声明 </em>或 <em>类表达式 </em>中用于创建一个类作为另一个类的一个子类。</p> -<pre class="brush: js notranslate">class Animal { +<pre class="brush: js">class Animal { constructor(name) { this.name = name; } @@ -283,7 +283,7 @@ d.speak();// 'Mitzie barks.' <p>也可以继承传统的基于函数的“类”:</p> -<pre class="brush: js notranslate">function Animal (name) { +<pre class="brush: js">function Animal (name) { this.name = name; } Animal.prototype.speak = function () { @@ -302,7 +302,7 @@ d.speak();//Mitzie makes a noise. Mitzie barks.</pre> <p>请注意,类不能继承常规对象(不可构造的)。如果要继承常规对象,可以改用{{jsxref("Object.setPrototypeOf()")}}:</p> -<pre class="brush: js notranslate">var Animal = { +<pre class="brush: js">var Animal = { speak() { console.log(this.name + ' makes a noise.'); } @@ -325,7 +325,7 @@ d.speak(); // Mitzie makes a noise.</pre> <p>例如,当使用像{{jsxref("Array.map", "map()")}}返回默认构造函数的方法时,您希望这些方法返回一个父<code>Array</code>对象,而不是<code>MyArray</code>对象。{{jsxref("Symbol.species")}} 符号可以让你这样做:</p> -<pre class="brush: js notranslate">class MyArray extends Array { +<pre class="brush: js">class MyArray extends Array { // Overwrite species to the parent Array constructor static get [Symbol.species]() { return Array; } } @@ -342,7 +342,7 @@ console.log(mapped instanceof Array); <p><code><a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/super">super</a></code> 关键字用于调用对象的父对象上的函数。</p> -<pre class="brush: js notranslate">class Cat { +<pre class="brush: js">class Cat { constructor(name) { this.name = name; } @@ -366,7 +366,7 @@ class Lion extends Cat { <p>一个以超类作为输入的函数和一个继承该超类的子类作为输出可以用于在ECMAScript中实现混合:</p> -<pre class="brush: js notranslate">var calculatorMixin = Base => class extends Base { +<pre class="brush: js">var calculatorMixin = Base => class extends Base { calc() { } }; @@ -376,7 +376,7 @@ var randomizerMixin = Base => class extends Base { <p>使用 mix-ins 的类可以像下面这样写:</p> -<pre class="brush: js notranslate">class Foo { } +<pre class="brush: js">class Foo { } class Bar extends calculatorMixin(randomizerMixin(Foo)) { }</pre> <h2 id="规范">规范</h2> diff --git a/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.html b/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.html index 9ab3cb7b02..b729af45fa 100644 --- a/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.html +++ b/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.html @@ -14,7 +14,7 @@ translation_of: Web/JavaScript/Reference/Errors/Cyclic_object_value <h2 id="提示信息">提示信息</h2> -<pre class="notranslate">TypeError: cyclic object value (Firefox) +<pre>TypeError: cyclic object value (Firefox) TypeError: Converting circular structure to JSON (Chrome and Opera) TypeError: Circular reference in value argument not supported (Edge)</pre> @@ -34,7 +34,7 @@ TypeError: Circular reference in value argument not supported (Edge)</pre> <p>在如下循环结构中:</p> -<pre class="brush: js notranslate">var a = {}; +<pre class="brush: js">var a = {}; var b = {}; a.child = b; b.child = a; @@ -42,7 +42,7 @@ b.child = a; <p>{{jsxref("JSON.stringify()")}} 将会报错</p> -<pre class="brush: js example-bad notranslate">JSON.stringify(a); +<pre class="brush: js example-bad">JSON.stringify(a); // TypeError: cyclic object value </pre> @@ -52,7 +52,7 @@ b.child = a; <p>注意:以下代码并不会保存循环引用的值。</p> -<pre class="brush: js example-good notranslate">var seen = []; +<pre class="brush: js example-good">var seen = []; var replacer = function(key, value) { if (typeof value === "object" && value !== null) { diff --git a/files/zh-cn/web/javascript/reference/errors/not_a_function/index.html b/files/zh-cn/web/javascript/reference/errors/not_a_function/index.html index fc4f664e1d..00c3cb3073 100644 --- a/files/zh-cn/web/javascript/reference/errors/not_a_function/index.html +++ b/files/zh-cn/web/javascript/reference/errors/not_a_function/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Errors/Not_a_function <h2 id="信息">信息</h2> -<pre class="notranslate">TypeError: Object doesn't support property or method {x} (Edge) +<pre>TypeError: Object doesn't support property or method {x} (Edge) TypeError: "x" is not a function</pre> <h2 id="错误类型">错误类型</h2> @@ -47,20 +47,20 @@ TypeError: "x" is not a function</pre> <p>函数的名称拼写错误,这种情况是经常发生的:</p> -<pre class="brush: js example-bad notranslate">var x = document.getElementByID("foo"); +<pre class="brush: js example-bad">var x = document.getElementByID("foo"); // TypeError: document.getElementByID is not a function </pre> <p>正确的方法名应该是 <code>getElementByI<strong>d:</strong></code></p> -<pre class="brush: js example-good notranslate">var x = document.getElementById("foo"); +<pre class="brush: js example-good">var x = document.getElementById("foo"); </pre> <h3 id="调用Object类型中不存在的方法">调用Object类型中不存在的方法</h3> <p>对于某些特殊的方法,它只属于某些特定的原生对象中,你必须提供一个回调函数才能正常运行。例如:这里调用了一个 {{jsxref("Array.prototype.map()")}} 方法,但是这方法只能被 {{jsxref("Array")}} 对象所调用。 </p> -<pre class="brush: js example-bad notranslate">var obj = { a: 13, b: 37, c: 42 }; +<pre class="brush: js example-bad">var obj = { a: 13, b: 37, c: 42 }; obj.map(function(num) { return num * 2; @@ -70,7 +70,7 @@ obj.map(function(num) { <p>正确的做法,使用一个数组来代替:</p> -<pre class="brush: js example-good notranslate">var numbers = [1, 4, 9]; +<pre class="brush: js example-good">var numbers = [1, 4, 9]; numbers.map(function(num) { return num * 2; @@ -83,7 +83,7 @@ numbers.map(function(num) { <p>当您在创建类时,可能会存在某个属性和某个方法的名称相同,当您在调用该函数时,编译器会认为该函数不存在.</p> -<pre class="brush: js example-bad notranslate">var Dog = function () { +<pre class="brush: js example-bad">var Dog = function () { this.age = 11; this.color = "black"; this.name = "Ralph"; @@ -102,7 +102,7 @@ myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function <p>正确的做法是使用不同的变量名.</p> -<pre class="brush: js example-good notranslate">var Dog = function () { +<pre class="brush: js example-good">var Dog = function () { this.age = 11; this.color = "black"; this.dogName = "Ralph"; //Using this.dogName instead of .name @@ -124,13 +124,13 @@ myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }< <p>使用后者时将会抛出错误:</p> -<pre class="brush: js example-bad notranslate">const sixteen = 2(3 + 5); +<pre class="brush: js example-bad">const sixteen = 2(3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //Uncaught TypeError: 2 is not a function</pre> <p>您可以添加乘法运算符 <code>*</code> 来改正代码:</p> -<pre class="brush: js example-good notranslate">const sixteen = 2 * (3 + 5); +<pre class="brush: js example-good">const sixteen = 2 * (3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //2 x (3 + 5) is 16</pre> @@ -140,7 +140,7 @@ alert('2 x (3 + 5) is ' + String(sixteen)); <p>以下为一个示例模块 (<code>helpers.js</code>)</p> -<pre class="notranslate">let helpers = function () { }; +<pre>let helpers = function () { }; helpers.groupBy = function (objectArray, property) { return objectArray.reduce(function (acc, obj) { @@ -158,7 +158,7 @@ export default helpers;</pre> <p>在 <code>App.js</code>中正确导入该模块:</p> -<pre class="notranslate">import helpers from './helpers'</pre> +<pre>import helpers from './helpers'</pre> <h2 id="相关">相关</h2> diff --git a/files/zh-cn/web/javascript/reference/errors/not_defined/index.html b/files/zh-cn/web/javascript/reference/errors/not_defined/index.html index a092f394ec..cc5fadb2a8 100644 --- a/files/zh-cn/web/javascript/reference/errors/not_defined/index.html +++ b/files/zh-cn/web/javascript/reference/errors/not_defined/index.html @@ -7,7 +7,7 @@ translation_of: Web/JavaScript/Reference/Errors/Not_defined <h2 id="错误信息">错误信息</h2> -<pre class="syntaxbox notranslate">ReferenceError: "x" is not defined +<pre class="syntaxbox">ReferenceError: "x" is not defined </pre> <h2 id="错误类型">错误类型</h2> @@ -26,19 +26,19 @@ translation_of: Web/JavaScript/Reference/Errors/Not_defined <h3 id="变量没有被声明">变量没有被声明</h3> -<pre class="brush: js example-bad notranslate">foo.substring(1); // ReferenceError: foo is not defined +<pre class="brush: js example-bad">foo.substring(1); // ReferenceError: foo is not defined </pre> <p>“foo” 变量没有在任何地方被声明。它需要是某种字符串,这样 {{jsxref("String.prototype.substring()")}} 方法才可以正常工作。</p> -<pre class="brush: js example-good notranslate">var foo = 'bar'; +<pre class="brush: js example-good">var foo = 'bar'; foo.substring(1); // "ar"</pre> <h3 id="错误的作用域">错误的作用域</h3> <p>变量必须是在它当前的执行环境中可用的。在一个函数(<a href="/en-US/docs/Web/JavaScript/Reference/Functions">function</a>)中定义的变量不能从这个函数外部的任何地方访问,因为这个变量的作用域仅在这个函数的内部。</p> -<pre class="brush: js example-bad notranslate">function numbers () { +<pre class="brush: js example-bad">function numbers () { var num1 = 2, num2 = 3; return num1 + num2; @@ -48,7 +48,7 @@ console.log(num1); // ReferenceError num1 is not defined.</pre> <p>然而,一个函数可用使用在它所被定义的作用域中的所有变量。换句话说,当一个函数被定义在全局作用域的时候,它可以访问所有在全局作用域中定义的变量。</p> -<pre class="brush: js example-good notranslate">var num1 = 2, +<pre class="brush: js example-good">var num1 = 2, num2 = 3; function numbers () { diff --git a/files/zh-cn/web/javascript/reference/functions/arguments/index.html b/files/zh-cn/web/javascript/reference/functions/arguments/index.html index 0cc7216837..8aff3819bd 100644 --- a/files/zh-cn/web/javascript/reference/functions/arguments/index.html +++ b/files/zh-cn/web/javascript/reference/functions/arguments/index.html @@ -35,18 +35,18 @@ translation_of: Web/JavaScript/Reference/Functions/arguments <p><code>arguments</code>对象是所有(非箭头)函数中都可用的<strong>局部变量</strong>。你可以使用<code>arguments</code>对象在函数中引用函数的参数。此对象包含传递给函数的每个参数,第一个参数在索引0处。例如,如果一个函数传递了三个参数,你可以以如下方式引用他们:</p> -<pre class="brush: js notranslate">arguments[0] +<pre class="brush: js">arguments[0] arguments[1] arguments[2] </pre> <p>参数也可以被设置:</p> -<pre class="brush: js notranslate">arguments[1] = 'new value';</pre> +<pre class="brush: js">arguments[1] = 'new value';</pre> <p><code>arguments</code>对象不是一个 {{jsxref("Array")}} 。它类似于<code>Array</code>,但除了length属性和索引元素之外没有任何<code>Array</code>属性。例如,它没有 <a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/pop" title="JavaScript/Reference/Global_Objects/Array/pop">pop</a> 方法。但是它可以被转换为一个真正的<code>Array</code>:</p> -<pre class="brush: js notranslate">var args = Array.prototype.slice.call(arguments); +<pre class="brush: js">var args = Array.prototype.slice.call(arguments); var args = [].slice.call(arguments); // ES2015 @@ -57,7 +57,7 @@ const args = [...arguments]; <div class="warning"> <p>对参数使用slice会阻止某些JavaScript引擎中的优化 (比如 V8 - <a href="https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments">更多信息</a>)。如果你关心性能,尝试通过遍历arguments对象来构造一个新的数组。另一种方法是使用被忽视的<code>Array</code>构造函数作为一个函数:</p> -<pre class="brush: js notranslate">var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)); +<pre class="brush: js">var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)); </pre> </div> @@ -67,7 +67,7 @@ const args = [...arguments]; <p>typeof参数返回 'object'。</p> -<pre class="brush: js notranslate">console.log(typeof arguments); // 'object' +<pre class="brush: js">console.log(typeof arguments); // 'object' // arguments 对象只能在函数内使用 function test(a){ console.log(a,Object.prototype.toString.call(arguments)); @@ -83,13 +83,13 @@ number <p>可以使用索引确定单个参数的类型。</p> -<pre class="brush: js notranslate">console.log(typeof arguments[0]); //this will return the typeof individual arguments.</pre> +<pre class="brush: js">console.log(typeof arguments[0]); //this will return the typeof individual arguments.</pre> <h3 id="对参数使用扩展语法">对参数使用扩展语法</h3> <p>您还可以使用{{jsxref("Array.from()")}}方法或<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_operator">扩展运算符</a>将参数转换为真实数组:</p> -<pre class="brush: js notranslate">var args = Array.from(arguments); +<pre class="brush: js">var args = Array.from(arguments); var args = [...arguments];</pre> <h2 id="Properties" name="Properties">属性</h2> @@ -120,7 +120,7 @@ var args = [...arguments];</pre> <h3 id="遍历参数求和">遍历参数求和</h3> -<pre class="brush: js notranslate">function add() { +<pre class="brush: js">function add() { var sum =0, len = arguments.length; for(var i=0; i<len; i++){ @@ -136,14 +136,14 @@ add(1,2,3,4); // 10</pre> <p>这个例子定义了一个函数来连接字符串。这个函数唯一正式声明了的参数是一个字符串,该参数指定一个字符作为衔接点来连接字符串。该函数定义如下:</p> -<pre class="brush:js notranslate">function myConcat(separator) { +<pre class="brush:js">function myConcat(separator) { var args = Array.prototype.slice.call(arguments, 1); return args.join(separator); }</pre> <p>你可以传递任意数量的参数到该函数,并使用每个参数作为列表中的项创建列表。</p> -<pre class="brush:js notranslate">// returns "red, orange, blue" +<pre class="brush:js">// returns "red, orange, blue" myConcat(", ", "red", "orange", "blue"); // returns "elephant; giraffe; lion; cheetah" @@ -156,7 +156,7 @@ myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");</pre> <p>这个例子定义了一个函数通过一个字符串来创建HTML列表。这个函数唯一正式声明了的参数是一个字符。当该参数为 "<code>u</code>" 时,创建一个无序列表 (项目列表);当该参数为 "<code>o</code>" 时,则创建一个有序列表 (编号列表)。该函数定义如下:</p> -<pre class="brush:js language-js notranslate" style="padding: 1em 0px 1em 30px; font-size: 14px; white-space: normal;"><code class="language-js" style="direction: ltr; white-space: pre;">function list(type) { +<pre class="brush:js language-js" style="padding: 1em 0px 1em 30px; font-size: 14px; white-space: normal;"><code class="language-js" style="direction: ltr; white-space: pre;">function list(type) { var result = "<" + type + "l><li>"; var args = Array.prototype.slice.call(arguments, 1); result += args.join("</li><li>"); @@ -167,7 +167,7 @@ myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");</pre> <p>你可以传递任意数量的参数到该函数,并将每个参数作为一个项添加到指定类型的列表中。例如:</p> -<pre class="brush:js language-js notranslate" style="padding: 1em 0px 1em 30px; font-size: 14px; white-space: normal;"><code class="language-js" style="direction: ltr; white-space: pre;">var listHTML = list("u", "One", "Two", "Three"); +<pre class="brush:js language-js" style="padding: 1em 0px 1em 30px; font-size: 14px; white-space: normal;"><code class="language-js" style="direction: ltr; white-space: pre;">var listHTML = list("u", "One", "Two", "Three"); /* listHTML is: @@ -180,7 +180,7 @@ myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");</pre> <p><code>arguments</code>对象可以与<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Rest_parameters">剩余参数</a>、<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Default_parameters">默认参数</a>和<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">解构赋值</a>参数结合使用。</p> -<pre class="brush: js notranslate">function foo(...args) { +<pre class="brush: js">function foo(...args) { return args; } foo(1, 2, 3); // [1,2,3] @@ -190,7 +190,7 @@ foo(1, 2, 3); // [1,2,3] <p>当非严格模式中的函数<strong>没有</strong>包含<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Rest_parameters">剩余参数</a>、<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Default_parameters">默认参数</a>和<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">解构赋值</a>,那么<code>arguments</code>对象中的值<strong>会</strong>跟踪参数的值(反之亦然)。看下面的代码:</p> -<pre class="brush: js notranslate">function func(a) { +<pre class="brush: js">function func(a) { arguments[0] = 99; // 更新了arguments[0] 同样更新了a console.log(a); } @@ -199,7 +199,7 @@ func(10); // 99 <p>并且</p> -<pre class="brush: js notranslate">function func(a) { +<pre class="brush: js">function func(a) { a = 99; // 更新了a 同样更新了arguments[0] console.log(arguments[0]); } @@ -208,7 +208,7 @@ func(10); // 99 <p>当非严格模式中的函数<strong>有</strong>包含<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Rest_parameters">剩余参数</a>、<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Default_parameters">默认参数</a>和<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">解构赋值</a>,那么<code>arguments</code>对象中的值<strong>不会</strong>跟踪参数的值(反之亦然)。相反, <code>arguments</code>反映了调用时提供的参数:</p> -<pre class="brush: js notranslate">function func(a = 55) { +<pre class="brush: js">function func(a = 55) { arguments[0] = 99; // updating arguments[0] does not also update a console.log(a); } @@ -216,7 +216,7 @@ func(10); // 10</pre> <p>并且</p> -<pre class="brush: js notranslate">function func(a = 55) { +<pre class="brush: js">function func(a = 55) { a = 99; // updating a does not also update arguments[0] console.log(arguments[0]); } @@ -224,7 +224,7 @@ func(10); // 10</pre> <p>并且</p> -<pre class="brush: js notranslate">function func(a = 55) { +<pre class="brush: js">function func(a = 55) { console.log(arguments[0]); } func(); // undefined diff --git a/files/zh-cn/web/javascript/reference/functions/arrow_functions/index.html b/files/zh-cn/web/javascript/reference/functions/arrow_functions/index.html index 7f3ca61168..a3166bf160 100644 --- a/files/zh-cn/web/javascript/reference/functions/arrow_functions/index.html +++ b/files/zh-cn/web/javascript/reference/functions/arrow_functions/index.html @@ -24,7 +24,7 @@ translation_of: Web/JavaScript/Reference/Functions/Arrow_functions <blockquote> <h3 class="brush: js" id="基础语法">基础语法</h3> -<pre class="notranslate">(param1, param2, …, paramN) => { statements } +<pre>(param1, param2, …, paramN) => { statements } (param1, param2, …, paramN) => expression //相当于:(param1, param2, …, paramN) =>{ return expression; } @@ -39,7 +39,7 @@ singleParam => { statements } <h3 id="高级语法">高级语法</h3> <blockquote> -<pre class="brush: js notranslate">//加括号的函数体返回对象字面量表达式: +<pre class="brush: js">//加括号的函数体返回对象字面量表达式: params => ({foo: bar}) //支持<strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/rest_parameters">剩余参数</a></strong>和<strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Default_parameters">默认参数</a></strong> @@ -60,7 +60,7 @@ f(); // 6</pre> <h3 id="更短的函数">更短的函数</h3> -<pre class="brush: js notranslate">var elements = [ +<pre class="brush: js">var elements = [ 'Hydrogen', 'Helium', 'Lithium', @@ -103,7 +103,7 @@ elements.map(({ "length": lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9] <p><code>This</code>被证明是令人厌烦的面向对象风格的编程。</p> -<pre class="brush: js notranslate">function Person() { +<pre class="brush: js">function Person() { // Person() 构造函数定义 `this`作为它自己的实例. this.age = 0; @@ -118,7 +118,7 @@ var p = new Person();</pre> <p>在ECMAScript 3/5中,通过将<code>this</code>值分配给封闭的变量,可以解决<code>this</code>问题。</p> -<pre class="brush: js notranslate">function Person() { +<pre class="brush: js">function Person() { var that = this; that.age = 0; @@ -132,7 +132,7 @@ var p = new Person();</pre> <p>箭头函数不会创建自己的<code>this,它只会从自己的作用域链的上一层继承this</code>。因此,在下面的代码中,传递给<code>setInterval</code>的函数内的<code>this</code>与封闭函数中的<code>this</code>值相同:</p> -<pre class="brush: js notranslate">function Person(){ +<pre class="brush: js">function Person(){ this.age = 0; setInterval(() => { @@ -146,7 +146,7 @@ var p = new Person();</pre> <p>鉴于 <code>this</code> 是词法层面上的,<a href="/zh-CN/docs/Web/JavaScript/Reference/Strict_mode">严格模式</a>中与 <code>this</code> 相关的规则都将被忽略。</p> -<pre class="notranslate"><code>var f = () => { 'use strict'; return this; }; +<pre><code>var f = () => { 'use strict'; return this; }; f() === window; // 或者 global</code></pre> <p>严格模式的其他规则依然不变.</p> @@ -155,7 +155,7 @@ f() === window; // 或者 global</code></pre> <p>由于 箭头函数没有自己的this指针,通过 <code>call()</code><em> 或</em> <code>apply()</code> 方法调用一个函数时,只能传递参数(不能绑定this---译者注),他们的第一个参数会被忽略。(这种现象对于bind方法同样成立---译者注)</p> -<pre class="brush: js notranslate">var adder = { +<pre class="brush: js">var adder = { base : 1, add : function(a) { @@ -180,7 +180,7 @@ console.log(adder.addThruCall(1)); // 仍然输出 2</pre> <p>箭头函数不绑定<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments">Arguments 对象</a>。因此,在本示例中,<code>arguments</code>只是引用了封闭作用域内的arguments:</p> -<pre class="brush: js notranslate">var arguments = [1, 2, 3]; +<pre class="brush: js">var arguments = [1, 2, 3]; var arr = () => arguments[0]; arr(); // 1 @@ -198,7 +198,7 @@ foo(3,2);//6 <p>在大多数情况下,使用<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Rest_parameters">剩余参数</a>是相较使用<code>arguments</code>对象的更好选择。</p> -<pre class="brush: js notranslate">function foo(arg) { +<pre class="brush: js">function foo(arg) { var f = (...args) => args[0]; return f(arg); } @@ -216,7 +216,7 @@ foo(1,2); //2 <p>如上所述,箭头函数表达式对非方法函数是最合适的。让我们看看当我们试着把它们作为方法时发生了什么。</p> -<pre class="brush: js notranslate">'use strict'; +<pre class="brush: js">'use strict'; var obj = { i: 10, b: () => console.log(this.i, this), @@ -232,7 +232,7 @@ obj.c(); <p>箭头函数没有定义this绑定。另一个涉及{{jsxref("Object.defineProperty()")}}的示例:</p> -<pre class="brush: js notranslate">'use strict'; +<pre class="brush: js">'use strict'; var obj = { a: 10 }; @@ -252,14 +252,14 @@ obj.b; // undefined "undefined" Window {postMessage: ƒ, blur: ƒ, focus: ƒ <p>箭头函数不能用作构造器,和 <code>new</code>一起用会抛出错误。</p> -<pre class="brush: js notranslate">var Foo = () => {}; +<pre class="brush: js">var Foo = () => {}; var foo = new Foo(); // TypeError: Foo is not a constructor</pre> <h3 id="使用prototype属性">使用<code>prototype</code>属性</h3> <p>箭头函数没有<code>prototype</code>属性。</p> -<pre class="brush: js notranslate">var Foo = () => {}; +<pre class="brush: js">var Foo = () => {}; console.log(Foo.prototype); // undefined</pre> <h3 id="使用_yield_关键字">使用 <code>yield</code> 关键字</h3> @@ -272,7 +272,7 @@ console.log(Foo.prototype); // undefined</pre> <p>在一个简写体中,只需要一个表达式,并附加一个隐式的返回值。在块体中,必须使用明确的<code>return</code>语句。</p> -<pre class="brush: js notranslate">var func = x => x * x; +<pre class="brush: js">var func = x => x * x; // 简写函数 省略return var func = (x, y) => { return x + y; }; @@ -282,7 +282,7 @@ var func = (x, y) => { return x + y; }; <p>记住用<code>params => {object:literal}</code>这种简单的语法返回对象字面量是行不通的。</p> -<pre class="brush: js notranslate">var func = () => { foo: 1 }; +<pre class="brush: js">var func = () => { foo: 1 }; // Calling func() returns undefined! var func = () => { foo: function() {} }; @@ -292,19 +292,19 @@ var func = () => { foo: function() {} }; <p>所以,记得用圆括号把对象字面量包起来:</p> -<pre class="brush: js notranslate">var func = () => ({foo: 1});</pre> +<pre class="brush: js">var func = () => ({foo: 1});</pre> <h2 id="换行">换行</h2> <p>箭头函数在参数和箭头之间不能换行。</p> -<pre class="brush: js notranslate">var func = () +<pre class="brush: js">var func = () => 1; // SyntaxError: expected expression, got '=>'</pre> <p>但是,可以通过在 ‘=>’ 之后换行,或者用 ‘( )’、'{ }'来实现换行,如下:</p> -<pre class="brush: js notranslate">var func = (a, b, c) => +<pre class="brush: js">var func = (a, b, c) => 1; var func = (a, b, c) => ( @@ -327,7 +327,7 @@ var func = ( <p>虽然箭头函数中的箭头不是运算符,但箭头函数具有与常规函数不同的特殊<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">运算符优先级</a>解析规则。</p> -<pre class="brush: js notranslate">let callback; +<pre class="brush: js">let callback; callback = callback || function() {}; // ok @@ -338,7 +338,7 @@ callback = callback || (() => {}); // ok</pre> <h2 id="更多示例">更多示例</h2> -<pre class="brush: js notranslate">// 空的箭头函数返回 undefined +<pre class="brush: js">// 空的箭头函数返回 undefined let empty = () => {}; (() => 'foobar')(); @@ -383,7 +383,7 @@ setTimeout( () => { <h4 id="箭头函数也可以使用条件(三元)运算符:">箭头函数也可以使用条件(三元)运算符:</h4> -<pre class="brush: js notranslate">var simple = a => a > 15 ? 15 : a; +<pre class="brush: js">var simple = a => a > 15 ? 15 : a; simple(16); // 15 simple(10); // 10 @@ -393,7 +393,7 @@ let max = (a, b) => a > b ? a : b;</pre> <p>箭头函数内定义的变量及其作用域</p> </blockquote> -<pre class="brush: js notranslate">// 常规写法 +<pre class="brush: js">// 常规写法 var greeting = () => {let now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));} greeting(); //"Good day." console.log(now); // ReferenceError: now is not defined 标准的let作用域 @@ -418,7 +418,7 @@ console.log(now); // ReferenceError: now is not defined <h4 id="箭头函数也可以使用闭包:">箭头函数也可以使用闭包:</h4> </blockquote> -<pre class="brush: js notranslate">// 标准的闭包函数 +<pre class="brush: js">// 标准的闭包函数 function A(){ var i=0; return function b(){ @@ -446,7 +446,7 @@ var Add = (i=0)=> ()=> (++i); <h4 id="箭头函数递归"> 箭头函数递归</h4> </blockquote> -<pre class="brush: js notranslate">var fact = (x) => ( x==0 ? 1 : x*fact(x-1) ); +<pre class="brush: js">var fact = (x) => ( x==0 ? 1 : x*fact(x-1) ); fact(5); // 120</pre> <p>规范</p> diff --git a/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/index.html b/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/index.html index c9578649f5..1802bbe483 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/index.html @@ -11,7 +11,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/AggregateError <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">new AggregateError(errors[, message])</pre> +<pre class="syntaxbox">new AggregateError(errors[, message])</pre> <h3 id="参数">参数</h3> @@ -50,7 +50,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/AggregateError <h3 id="捕获一个AggregateError">捕获一个AggregateError</h3> -<pre class="brush: js; notranslate">Promise.any([ +<pre class="brush: js;">Promise.any([ Promise.reject(new Error("some error")), ]).catch(e => { console.log(e instanceof AggregateError); // true @@ -62,7 +62,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/AggregateError <h3 id="创建一个AggregateError">创建一个AggregateError</h3> -<pre class="brush: js; notranslate">try { +<pre class="brush: js;">try { throw new AggregateError([ new Error("some error"), ], 'Hello'); diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/concat/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/concat/index.html index 4541912a76..b0960c35d0 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/concat/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/concat/index.html @@ -16,7 +16,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">var <var>new_array</var> = <var>old_array</var>.concat(<var>value1</var>[, <var>value2</var>[, ...[, <var>valueN</var>]]])</pre> +<pre class="syntaxbox">var <var>new_array</var> = <var>old_array</var>.concat(<var>value1</var>[, <var>value2</var>[, ...[, <var>valueN</var>]]])</pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -53,7 +53,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat <p>以下代码将两个数组合并为一个新数组:</p> -<pre class="brush: js notranslate">var alpha = ['a', 'b', 'c']; +<pre class="brush: js">var alpha = ['a', 'b', 'c']; var numeric = [1, 2, 3]; alpha.concat(numeric); @@ -63,7 +63,7 @@ alpha.concat(numeric); <p>以下代码将三个数组合并为一个新数组:</p> -<pre class="brush: js notranslate">var num1 = [1, 2, 3], +<pre class="brush: js">var num1 = [1, 2, 3], num2 = [4, 5, 6], num3 = [7, 8, 9]; @@ -76,7 +76,7 @@ console.log(nums); <p>以下代码将三个值连接到数组:</p> -<pre class="brush: js notranslate">var alpha = ['a', 'b', 'c']; +<pre class="brush: js">var alpha = ['a', 'b', 'c']; var alphaNumeric = alpha.concat(1, [2, 3]); @@ -87,7 +87,7 @@ console.log(alphaNumeric); <p>以下代码合并数组并保留引用:</p> -<pre class="brush: js notranslate">var num1 = [[1]]; +<pre class="brush: js">var num1 = [[1]]; var num2 = [2, [3]]; var num3=[5,[6]]; diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/every/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/every/index.html index a64c25b43d..38d4388b52 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/every/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/every/index.html @@ -24,7 +24,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/every <h2 id="语法">语法</h2> -<pre class="notranslate"><var>arr</var>.every(<var>callback</var>(<var>element</var>[, <var>index</var>[, <var>array</var>]])[, <var>thisArg</var>])</pre> +<pre><var>arr</var>.every(<var>callback</var>(<var>element</var>[, <var>index</var>[, <var>array</var>]])[, <var>thisArg</var>])</pre> <h3 id="参数">参数</h3> @@ -68,7 +68,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/every <p>下例检测数组中的所有元素是否都大于 10。</p> -<pre class="brush: js notranslate">function isBigEnough(element, index, array) { +<pre class="brush: js">function isBigEnough(element, index, array) { return element >= 10; } [12, 5, 8, 130, 44].every(isBigEnough); // false @@ -79,14 +79,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/every <p><a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions">箭头函数</a>为上面的检测过程提供了更简短的语法。</p> -<pre class="brush: js notranslate">[12, 5, 8, 130, 44].every(x => x >= 10); // false +<pre class="brush: js">[12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true</pre> <h2 id="兼容旧环境(Polyfill)">兼容旧环境(Polyfill)</h2> <p>在 ECMA-262 第 5 版时,<code>every</code> 被添加进 ECMA-262 标准;因此,在某些实现环境中,它尚未被支持。你可以把下面的代码放到脚本的开头来解决此问题,该代码允许在那些没有原生支持 <code>every</code> 的实现环境中使用它。该算法是 ECMA-262 第 5 版中指定的算法,它假定 <code>Object</code> 和 <code>TypeError</code> 拥有它们的初始值,且 <code>fun.call</code> 等价于 {{jsxref("Function.prototype.call")}}。</p> -<pre class="brush: js notranslate">if (!Array.prototype.every) { +<pre class="brush: js">if (!Array.prototype.every) { Array.prototype.every = function(callbackfn, thisArg) { 'use strict'; var T, k; diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/filter/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/filter/index.html index c23bf5cb98..acc86a9592 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/filter/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/filter/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>var newArray = arr</var>.filter(<var>callback(element[, index[, array]])</var>[, <var>thisArg</var>])</pre> +<pre class="syntaxbox"><var>var newArray = arr</var>.filter(<var>callback(element[, index[, array]])</var>[, <var>thisArg</var>])</pre> <h3 id="参数">参数</h3> @@ -69,7 +69,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter <p>下例使用 <code>filter</code> 创建了一个新数组,该数组的元素由原数组中值大于 10 的元素组成。</p> -<pre class="brush: js notranslate">function isBigEnough(element) { +<pre class="brush: js">function isBigEnough(element) { return element >= 10; } var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); @@ -80,7 +80,7 @@ var filtered = [12, 5, 8, 130, 44].filter(isBigEnough); <p>以下示例使用 <code>filter()</code> 创建具有非零 <code>id</code> 的元素的 json。</p> -<pre class="brush: js notranslate">var arr = [ +<pre class="brush: js">var arr = [ { id: 15 }, { id: -1 }, { id: 0 }, @@ -120,7 +120,7 @@ console.log('Number of Invalid Entries = ', invalidEntries); <p>下例使用 <code>filter()</code> 根据搜索条件来过滤数组内容。</p> -<pre class="brush: js notranslate">var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; +<pre class="brush: js">var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; /** * Array filters items based on search criteria (query) @@ -136,7 +136,7 @@ console.log(filterItems('an')); // ['banana', 'mango', 'orange']</pre> <h4 id="ES2015_实现">ES2015 实现</h4> -<pre class="brush: js notranslate">const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; +<pre class="brush: js">const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; /** * Array filters items based on search criteria (query) @@ -156,7 +156,7 @@ console.log(filterItems('an')); // ['banana', 'mango', 'orange'] <p><code>filter</code> 被添加到 ECMA-262 标准第 5 版中,因此在某些实现环境中不被支持。可以把下面的代码插入到脚本的开头来解决此问题,该代码允许在那些没有原生支持 <code>filter</code> 的实现环境中使用它。该算法是 ECMA-262 第 5 版中指定的算法,假定 <code>fn.call</code> 等价于 {{jsxref("Function.prototype.call")}} 的初始值,且 {{jsxref("Array.prototype.push")}} 拥有它的初始值。</p> -<pre class="brush: js notranslate">if (!Array.prototype.filter){ +<pre class="brush: js">if (!Array.prototype.filter){ Array.prototype.filter = function(func, thisArg) { 'use strict'; if ( ! ((typeof func === 'Function' || typeof func === 'function') && this) ) diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/findindex/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/findindex/index.html index 7b1e3c7143..b0c8967e8e 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/findindex/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/findindex/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code><em>arr</em>.findIndex(<em>callback</em>[, <em>thisArg</em>])</code></pre> +<pre class="syntaxbox"><code><em>arr</em>.findIndex(<em>callback</em>[, <em>thisArg</em>])</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -62,7 +62,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex <p>以下示例查找数组中素数的元素的索引(如果不存在素数,则返回-1)。</p> -<pre class="brush: js notranslate">function isPrime(element, index, array) { +<pre class="brush: js">function isPrime(element, index, array) { var start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) { @@ -77,7 +77,7 @@ console.log([4, 6, 7, 12].findIndex(isPrime)); // 2</pre> <h2 id="Polyfill">Polyfill</h2> -<pre class="brush: js notranslate">// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex +<pre class="brush: js">// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex if (!Array.prototype.findIndex) { Object.defineProperty(Array.prototype, 'findIndex', { value: function(predicate) { diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/flat/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/flat/index.html index 2f37e8f49b..f6a9420e21 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/flat/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/flat/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>var newArray = arr</var>.flat([<var>depth]</var>)</pre> +<pre class="syntaxbox"><var>var newArray = arr</var>.flat([<var>depth]</var>)</pre> <h3 id="参数">参数</h3> @@ -36,7 +36,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat <h3 id="扁平化嵌套数组">扁平化嵌套数组</h3> -<pre class="notranslate">var arr1 = [1, 2, [3, 4]]; +<pre>var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] @@ -57,7 +57,7 @@ arr4.flat(Infinity); <p><code>flat()</code> 方法会移除数组中的空项:</p> -<pre class="brush: js notranslate">var arr4 = [1, 2, , 4, 5]; +<pre class="brush: js">var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]</pre> @@ -65,7 +65,7 @@ arr4.flat(); <h3 id="使用_reduce_与_concat">使用 <code>reduce</code> 与 <code>concat</code></h3> -<pre class="notranslate"><code>var arr = [1, 2, [3, 4]]; +<pre><code>var arr = [1, 2, [3, 4]]; // 展开一层数组 arr.flat(); @@ -78,7 +78,7 @@ const flattened = arr => [].concat(...arr);</code></pre> <h3 class="brush: js" id="reduce_concat_isArray_recursivity">reduce + concat + isArray + recursivity</h3> -<pre class="brush: js notranslate"><code>// 使用 reduce、concat 和递归展开无限多层嵌套的数组 +<pre class="brush: js"><code>// 使用 reduce、concat 和递归展开无限多层嵌套的数组 var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]]; </code> <code class="language-js">function flatDeep(arr, d = 1) { @@ -91,7 +91,7 @@ flatDeep(arr1, Infinity); <h3 id="forEachisArraypushrecursivity">forEach+isArray+push+recursivity</h3> -<pre class="brush: js notranslate">// forEach 遍历数组会自动跳过空元素 +<pre class="brush: js">// forEach 遍历数组会自动跳过空元素 const eachFlat = (arr = [], depth = 1) => { const result = []; // 缓存递归结果 // 开始递归 @@ -131,7 +131,7 @@ const forFlat = (arr = [], depth = 1) => { <h3 id="使用堆栈stack">使用堆栈stack</h3> -<pre class="notranslate">// 无递归数组扁平化,使用堆栈 +<pre>// 无递归数组扁平化,使用堆栈 // 注意:深度的控制比较低效,因为需要检查每一个值的深度 // 也可能在 shift / unshift 上进行 w/o 反转,但是末端的数组 OPs 更快 var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]]; @@ -153,7 +153,7 @@ function flatten(input) { } flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]</pre> -<pre class="notranslate">// 递归版本的反嵌套 +<pre>// 递归版本的反嵌套 function flatten(array) { var flattend = []; (function flat(array) { @@ -167,7 +167,7 @@ function flatten(array) { <h3 id="Use_Generator_function">Use <code>Generator</code> function</h3> -<pre class="notranslate"><code>function* flatten(array) { +<pre><code>function* flatten(array) { for (const item of array) { if (Array.isArray(item)) { yield* flatten(item); diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/flatmap/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/flatmap/index.html index 50c75a73ab..8383d4be6a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/flatmap/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/flatmap/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/flatMap <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>var new_array = arr</var>.flatMap(function <var>callback(currentValue[, index[, array]]) { +<pre class="syntaxbox"><var>var new_array = arr</var>.flatMap(function <var>callback(currentValue[, index[, array]]) { // return element for new_array }</var>[, <var>thisArg</var>])</pre> @@ -54,7 +54,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/flatMap <h3 id="map_与_flatMap"><code>map()</code> 与 <code>flatMap()</code></h3> -<pre class="brush: js notranslate">var arr1 = [1, 2, 3, 4]; +<pre class="brush: js">var arr1 = [1, 2, 3, 4]; arr1.map(x => [x * 2]); // [[2], [4], [6], [8]] @@ -70,7 +70,7 @@ arr1.flatMap(x => [[x * 2]]); <p>所以,为了更好的展示 flatMap 的作用,下面我们将包含几句话的数组拆分成单个词组成的新数组。</p> -<pre class="notranslate"><code>let arr1 = ["it's Sunny in", "", "California"]; +<pre><code>let arr1 = ["it's Sunny in", "", "California"]; arr1.map(x => x.split(" ")); // [["it's","Sunny","in"],[""],["California"]] @@ -84,7 +84,7 @@ arr1.flatMap(x => x.split(" ")); <p><code>flatMap</code> 能用于在map期间增删项目(也就是修改items的数量)。换句话说,它允许你遍历很多项使之成为另一些项(靠分别把它们放进去来处理),而不是总是一对一。 从这个意义上讲,它的作用类似于 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter">filter</a>的对立面。只需返回一个1项元素数组以保留该项,返回一个多元素数组以添加项,或返回一个0项元素数组以删除该项。</p> -<pre class="notranslate"><code>// Let's say we want to remove all the negative numbers and split the odd numbers into an even number and a 1 +<pre><code>// Let's say we want to remove all the negative numbers and split the odd numbers into an even number and a 1 let a = [5, 4, -3, 20, 17, -33, -4, 18] // |\ \ x | | \ x x | // [4,1, 4, 20, 16, 1, 18] @@ -101,7 +101,7 @@ a.flatMap( (n) => <h3 id="reduce_与_concat"><code>reduce()</code> 与 <code>concat()</code></h3> -<pre class="notranslate"><code>var arr = [1, 2, 3, 4]; +<pre><code>var arr = [1, 2, 3, 4]; arr.flatMap(x => [x, x * 2]); // is equivalent to diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/from/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/from/index.html index 8cab100d7c..01b6062f91 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/from/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/from/index.html @@ -22,7 +22,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/from <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">Array.from(<em>arrayLike</em>[, <em>mapFn</em>[, <em>thisArg</em>]]) +<pre class="syntaxbox">Array.from(<em>arrayLike</em>[, <em>mapFn</em>[, <em>thisArg</em>]]) </pre> <h3 id="参数">参数</h3> @@ -59,18 +59,18 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/from <h3 id="从_String_生成数组">从 <code>String</code> 生成数组</h3> -<pre class="brush: js notranslate">Array.from('foo'); +<pre class="brush: js">Array.from('foo'); // [ "f", "o", "o" ]</pre> <h3 id="从_Set_生成数组">从 <code>Set</code> 生成数组</h3> -<pre class="brush: js notranslate">const set = new Set(['foo', 'bar', 'baz', 'foo']); +<pre class="brush: js">const set = new Set(['foo', 'bar', 'baz', 'foo']); Array.from(set); // [ "foo", "bar", "baz" ]</pre> <h3 id="从_Map_生成数组">从 <code>Map</code> 生成数组</h3> -<pre class="brush: js notranslate">const map = new Map([[1, 2], [2, 4], [4, 8]]); +<pre class="brush: js">const map = new Map([[1, 2], [2, 4], [4, 8]]); Array.from(map); // [[1, 2], [2, 4], [4, 8]] @@ -84,7 +84,7 @@ Array.from(mapper.keys()); <h3 id="从类数组对象(arguments)生成数组">从类数组对象(arguments)生成数组</h3> -<pre class="brush: js notranslate">function f() { +<pre class="brush: js">function f() { return Array.from(arguments); } @@ -94,7 +94,7 @@ f(1, 2, 3); <h3 id="在_Array.from_中使用箭头函数">在 <code>Array.from</code> 中使用箭头函数</h3> -<pre class="brush: js notranslate">// Using an arrow function as the map function to +<pre class="brush: js">// Using an arrow function as the map function to // manipulate the elements Array.from([1, 2, 3], x => x + x); // [2, 4, 6] @@ -109,7 +109,7 @@ Array.from({length: 5}, (v, i) => i); <h3 id="序列生成器指定范围">序列生成器(指定范围)</h3> -<pre class="brush: js notranslate">// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc) +<pre class="brush: js">// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc) const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step)); // Generate numbers range 0..4 @@ -127,7 +127,7 @@ range('A'.charCodeAt(0), 'Z'.charCodeAt(0), 1).map(x => String.fromCharCode(x <h3 id="数组去重合并">数组去重合并</h3> -<pre class="brush: js notranslate">function combine(){ +<pre class="brush: js">function combine(){ let arr = [].concat.apply([], arguments); //没有去重复的新数组 return Array.from(new Set(arr)); } @@ -139,7 +139,7 @@ console.log(combine(m,n)); // [1, 2, 3]</pre> <p>ECMA-262 第六版标准中添加了 <code>Array.from </code>。有些实现中可能尚未包括在其中。你可以通过在脚本前添加如下内容作为替代方法,以使用未原生支持的 <code>Array.from</code> 方法。该算法按照 ECMA-262 第六版中的规范实现,并假定 <code>Object</code> 和 <code>TypeError</code> 有其本身的值, <code>callback.call</code> 对应 {{jsxref("Function.prototype.call")}} 。此外,鉴于无法使用 Polyfill 实现真正的的迭代器,该实现不支持规范中定义的泛型可迭代元素。</p> -<pre class="brush: js notranslate">// Production steps of ECMA-262, Edition 6, 22.1.2.1 +<pre class="brush: js">// Production steps of ECMA-262, Edition 6, 22.1.2.1 if (!Array.from) { Array.from = (function () { var toStr = Object.prototype.toString; diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/map/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/map/index.html index b00ce5df07..1517622c81 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/map/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/map/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/map <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="notranslate"><var>var new_array = arr</var>.map(function <var>callback(currentValue[, index[, array]]) { +<pre><var>var new_array = arr</var>.map(function <var>callback(currentValue[, index[, array]]) { // Return element for new_array </var> <var>}</var>[, <var>thisArg</var>])</pre> @@ -68,7 +68,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/map <p>下面的代码创建了一个新数组,值为原数组中对应数字的平方根。</p> -<pre class="brush: js notranslate">var numbers = [1, 4, 9]; +<pre class="brush: js">var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); // roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]</pre> @@ -76,7 +76,7 @@ var roots = numbers.map(Math.sqrt); <p>以下代码使用一个包含对象的数组来重新创建一个格式化后的数组。</p> -<pre class="brush: js notranslate">var kvArray = [{key: 1, value: 10}, +<pre class="brush: js">var kvArray = [{key: 1, value: 10}, {key: 2, value: 20}, {key: 3, value: 30}]; @@ -98,7 +98,7 @@ var reformattedArray = kvArray.map(function(obj) { <p>下面的代码表示了当函数需要一个参数时map的工作方式。当map循环遍历原始数组时,这个参数会自动被分配成数组中对应的每个元素。</p> -<pre class="brush: js notranslate">var numbers = [1, 4, 9]; +<pre class="brush: js">var numbers = [1, 4, 9]; var doubles = numbers.map(function(num) { return num * 2; }); @@ -110,7 +110,7 @@ var doubles = numbers.map(function(num) { <p>下面的例子演示如何在一个 {{jsxref("String")}} 上使用 map 方法获取字符串中每个字符所对应的 ASCII 码组成的数组:</p> -<pre class="brush: js notranslate">var map = Array.prototype.map +<pre class="brush: js">var map = Array.prototype.map var a = map.call("Hello World", function(x) { return x.charCodeAt(0); }) @@ -121,7 +121,7 @@ var a = map.call("Hello World", function(x) { <p>下面代码展示了如何去遍历用 <code>querySelectorAll </code>得到的动态对象集合。在这里,我们获得了文档里所有选中的选项,并将其打印:</p> -<pre class="brush: js notranslate">var elems = document.querySelectorAll('select option:checked'); +<pre class="brush: js">var elems = document.querySelectorAll('select option:checked'); var values = Array.prototype.map.call(elems, function(obj) { return obj.value; }); @@ -135,7 +135,7 @@ var values = Array.prototype.map.call(elems, function(obj) { <p>考虑下例:</p> -<pre class="notranslate"><code>["1", "2", "3"].map(parseInt);</code></pre> +<pre><code>["1", "2", "3"].map(parseInt);</code></pre> <p>我们期望输出 <code>[1, 2, 3]</code>, 而实际结果是 <code>[1, NaN, NaN]</code>.</p> @@ -149,14 +149,14 @@ var values = Array.prototype.map.call(elems, function(obj) { <p>第三个参数被parseInt忽视了, <u>but not the second one</u>, 但不是第二个。因此可能出现混淆。下面是迭代步骤的简明示例:</p> -<pre class="notranslate"><code>// parseInt(string, radix) -> map(parseInt(value, index)) +<pre><code>// parseInt(string, radix) -> map(parseInt(value, index)) /* first iteration (index is 0): */ parseInt("1", 0); // 1 /* second iteration (index is 1): */ parseInt("2", 1); // NaN /* third iteration (index is 2): */ parseInt("3", 2); // NaN</code></pre> <p>下面让我们来讨论解决方案:</p> -<pre class="notranslate"><code>function returnInt(element) { +<pre><code>function returnInt(element) { return parseInt(element, 10); } @@ -176,7 +176,7 @@ var values = Array.prototype.map.call(elems, function(obj) { <p>一个map方法调用 parseInt 作为一个参数的等效输出运行如下:</p> -<pre class="notranslate"><code>var xs = ['10', '10', '10']; +<pre><code>var xs = ['10', '10', '10']; xs = xs.map(parseInt); @@ -187,7 +187,7 @@ console.log(xs); // 输出结果为</code>(3) [10, NaN, 2]<code> <p>当返回undefined 或没有返回任何内容时:</p> -<pre class="notranslate"><code>var numbers = [1, 2, 3, 4]; +<pre><code>var numbers = [1, 2, 3, 4]; var filteredNumbers = numbers.map(function(num, index) { if(index < 3) { return num; @@ -201,7 +201,7 @@ var filteredNumbers = numbers.map(function(num, index) { <p><code>map</code> was added to the ECMA-262 standard in the 5th edition; as such it may not be present in all implementations of the standard. You can work around this by inserting the following code at the beginning of your scripts, allowing use of <code>map</code> in implementations which do not natively support it. This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming {{jsxref("Object")}}, {{jsxref("TypeError")}}, and {{jsxref("Array")}} have their original values and that <code>callback.call</code> evaluates to the original value of <code>{{jsxref("Function.prototype.call")}}</code>.</p> -<pre class="notranslate"><code>// Production steps of ECMA-262, Edition 5, 15.4.4.19 +<pre><code>// Production steps of ECMA-262, Edition 5, 15.4.4.19 // Reference: http://es5.github.io/#x15.4.4.19 if (!Array.prototype.map) { diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/reduce/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/reduce/index.html index f356bceaf6..cc217e28af 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/reduce/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/reduce/index.html @@ -36,7 +36,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce <h2 id="语法">语法</h2> -<pre class="notranslate"><var>arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])</var></pre> +<pre><var>arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])</var></pre> <h3 id="参数">参数</h3> @@ -89,7 +89,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce <p>提供初始值通常更安全,正如下面的例子,如果没有提供<code>initialValue</code>,则可能有四种输出:</p> -<pre class="brush: js notranslate">var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x ); +<pre class="brush: js">var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x ); var maxCallback2 = ( max, cur ) => Math.max( max, cur ); // reduce() 没有初始值 @@ -107,7 +107,7 @@ var maxCallback2 = ( max, cur ) => Math.max( max, cur ); <p>假如运行下段<code>reduce()</code>代码:</p> -<pre class="brush:js notranslate">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){ +<pre class="brush:js">[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){ return accumulator + currentValue; }); </pre> @@ -172,11 +172,11 @@ var maxCallback2 = ( max, cur ) => Math.max( max, cur ); <p>你还可以使用{{jsxref("Functions/Arrow_functions", "箭头函数","",1)}}来代替完整的函数。 下面的代码将产生与上面的代码相同的输出:</p> -<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr );</pre> +<pre class="brush: js">[0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr );</pre> <p>如果你打算提供一个初始值作为<code>reduce()</code>方法的第二个参数,以下是运行过程及结果:</p> -<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { +<pre class="brush: js">[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue }, 10) </pre> @@ -332,14 +332,14 @@ var maxCallback2 = ( max, cur ) => Math.max( max, cur ); <h3 id="数组里所有值的和">数组里所有值的和</h3> -<pre class="brush: js notranslate">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { +<pre class="brush: js">var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) { return accumulator + currentValue; }, 0); // 和为 6</pre> <p>你也可以写成箭头函数的形式:</p> -<pre class="brush: js notranslate">var total = [ 0, 1, 2, 3 ].reduce( +<pre class="brush: js">var total = [ 0, 1, 2, 3 ].reduce( ( acc, cur ) => acc + cur, 0 );</pre> @@ -348,7 +348,7 @@ var maxCallback2 = ( max, cur ) => Math.max( max, cur ); <p>要累加对象数组中包含的值,必须提供初始值,以便各个item正确通过你的函数。</p> -<pre class="brush: js notranslate">var initialValue = 0; +<pre class="brush: js">var initialValue = 0; var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) { return accumulator + currentValue.x; },initialValue) @@ -357,7 +357,7 @@ console.log(sum) // logs 6</pre> <p>你也可以写成箭头函数的形式:</p> -<pre class="brush: js notranslate">var initialValue = 0; +<pre class="brush: js">var initialValue = 0; var sum = [{x: 1}, {x:2}, {x:3}].reduce( (accumulator, currentValue) => accumulator + currentValue.x ,initialValue @@ -368,7 +368,7 @@ console.log(sum) // logs 6 <h3 id="将二维数组转化为一维">将二维数组转化为一维</h3> -<pre class="brush: js notranslate">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( function(a, b) { return a.concat(b); }, @@ -379,7 +379,7 @@ console.log(sum) // logs 6 <p>你也可以写成箭头函数的形式:</p> -<pre class="brush: js notranslate">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduce( ( acc, cur ) => acc.concat(cur), [] ); @@ -388,7 +388,7 @@ console.log(sum) // logs 6 <h3 id="计算数组中每个元素出现的次数">计算数组中每个元素出现的次数</h3> -<pre class="brush: js notranslate">var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; +<pre class="brush: js">var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice']; var countedNames = names.reduce(function (allNames, name) { if (name in allNames) { @@ -404,7 +404,7 @@ var countedNames = names.reduce(function (allNames, name) { <h3 id="按属性对object分类">按属性对object分类</h3> -<pre class="brush: js notranslate">var people = [ +<pre class="brush: js">var people = [ { name: 'Alice', age: 21 }, { name: 'Max', age: 20 }, { name: 'Jane', age: 20 } @@ -434,7 +434,7 @@ var groupedPeople = groupBy(people, 'age'); <h3 id="使用扩展运算符和initialValue绑定包含在对象数组中的数组">使用扩展运算符和initialValue绑定包含在对象数组中的数组</h3> -<pre class="brush: js notranslate">// friends - 对象数组 +<pre class="brush: js">// friends - 对象数组 // where object field "books" - list of favorite books var friends = [{ name: 'Anna', @@ -469,7 +469,7 @@ var allbooks = friends.reduce(function(prev, curr) { <p>注意: 如果你正在使用一个可以兼容{{jsxref("Set")}} 和 {{jsxref("Array.from()")}} 的环境, 你可以使用<code>let orderedArray = Array.from(new Set(myArray));</code> 来获得一个相同元素被移除的数组。</p> </div> -<pre class="brush: js notranslate">let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'] +<pre class="brush: js">let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'] let myOrderedArray = myArray.reduce(function (accumulator, currentValue) { if (accumulator.indexOf(currentValue) === -1) { accumulator.push(currentValue) @@ -479,7 +479,7 @@ let myOrderedArray = myArray.reduce(function (accumulator, currentValue) { console.log(myOrderedArray)</pre> -<pre class="brush: js notranslate">let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4]; +<pre class="brush: js">let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4]; let result = arr.sort().reduce((init, current) => { if(init.length === 0 || init[init.length-1] !== current) { init.push(current); @@ -490,7 +490,7 @@ console.log(result); //[1,2,3,4,5]</pre> <h3 id="按顺序运行Promise">按顺序运行Promise</h3> -<pre class="brush: js notranslate">/** +<pre class="brush: js">/** * Runs promises from array of functions that can return promises * in chained manner * @@ -537,7 +537,7 @@ runPromiseInSequence(promiseArr, 10) <h3 id="功能型函数管道">功能型函数管道</h3> -<pre class="brush: js notranslate">// Building-blocks to use for composition +<pre class="brush: js">// Building-blocks to use for composition const double = x => x + x; const triple = x => 3 * x; const quadruple = x => 4 * x; @@ -563,7 +563,7 @@ multiply24(10); // 240 <h3 id="使用_reduce实现map">使用 reduce实现map</h3> -<pre class="brush: js notranslate">if (!Array.prototype.mapUsingReduce) { +<pre class="brush: js">if (!Array.prototype.mapUsingReduce) { Array.prototype.mapUsingReduce = function(callback, thisArg) { return this.reduce(function(mappedArray, currentValue, index, array) { mappedArray[index] = callback.call(thisArg, currentValue, index, array) @@ -579,7 +579,7 @@ multiply24(10); // 240 <h2 id="Polyfill">Polyfill</h2> -<pre class="brush: js notranslate">// Production steps of ECMA-262, Edition 5, 15.4.4.21 +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.21 // Reference: http://es5.github.io/#x15.4.4.21 // https://tc39.github.io/ecma262/#sec-array.prototype.reduce if (!Array.prototype.reduce) { diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/reduceright/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/reduceright/index.html index 94ef4c7602..1245486db3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/reduceright/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/reduceright/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])</var></pre> +<pre class="syntaxbox"><var>arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])</var></pre> <h3 id="参数">参数</h3> @@ -55,7 +55,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight <p>可以像下面这样调用 <code>reduceRight</code> 的回调函数 <code>callback</code>:</p> -<pre class="brush: js notranslate">array.reduceRight(function(accumulator, currentValue, index, array) { +<pre class="brush: js">array.reduceRight(function(accumulator, currentValue, index, array) { // ... });</pre> @@ -111,7 +111,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight <p>该函数的完整执行过程见下例:</p> -<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) { +<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) { return previousValue + currentValue; }); </pre> @@ -169,7 +169,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight <p>如果提供了一个 <code>initialValue</code> 参数,则结果如下:</p> -<pre class="brush: js notranslate">[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) { +<pre class="brush: js">[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) { return previousValue + currentValue; }, 10); </pre> @@ -235,14 +235,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight <h3 id="求一个数组中所有值的和">求一个数组中所有值的和</h3> -<pre class="brush: js notranslate">var sum = [0, 1, 2, 3].reduceRight(function(a, b) { +<pre class="brush: js">var sum = [0, 1, 2, 3].reduceRight(function(a, b) { return a + b; }); // sum is 6</pre> <h3 id="扁平化(flatten)一个二维数组">扁平化(flatten)一个二维数组</h3> -<pre class="brush: js notranslate">var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { +<pre class="brush: js">var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) { return a.concat(b); }, []); // flattened is [4, 5, 2, 3, 0, 1] @@ -250,7 +250,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight <h3 id="运行一个带有回调每个函数将其结果传给下一个的异步函数列表">运行一个带有回调每个函数将其结果传给下一个的异步函数列表</h3> -<pre class="brush: js notranslate">const waterfall = (...functions) => (callback, ...args) => +<pre class="brush: js">const waterfall = (...functions) => (callback, ...args) => functions.reduceRight( (composition, fn) => (...results) => fn(composition, ...results), callback @@ -293,7 +293,7 @@ const computation2 = (input, callback) => { <h3 id="展示_reduce_与_reduceRight_之间的区别">展示 <code>reduce</code> 与 <code>reduceRight</code> 之间的区别</h3> -<pre class="brush: js notranslate">var a = ['1', '2', '3', '4', '5']; +<pre class="brush: js">var a = ['1', '2', '3', '4', '5']; var left = a.reduce(function(prev, cur) { return prev + cur; }); var right = a.reduceRight(function(prev, cur) { return prev + cur; }); @@ -304,7 +304,7 @@ console.log(right); // "54321"</pre> <p>组合函数的概念简单,它只是简单地结合了多个函数。它是一个从右向左流动的函数,用上一个函数的输出调用每个函数。</p> -<pre class="brush: js notranslate">/** +<pre class="brush: js">/** * Function Composition is way in which result of one function can * be passed to another and so on. * @@ -333,7 +333,7 @@ console.log(compose(inc, double)(2)); // 5</pre> <p><code>reduceRight</code> 被添加到 ECMA-262 标准第 5 版,因此它在某些实现环境中可能不被支持。把下面的代码添加到脚本开头可以解决此问题,从而允许在那些没有原生支持 <code>reduceRight</code> 的实现环境中使用它。</p> -<pre class="brush: js notranslate">// Production steps of ECMA-262, Edition 5, 15.4.4.22 +<pre class="brush: js">// Production steps of ECMA-262, Edition 5, 15.4.4.22 // Reference: http://es5.github.io/#x15.4.4.22 if ('function' !== typeof Array.prototype.reduceRight) { Array.prototype.reduceRight = function(callback /*, initialValue*/) { diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/slice/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/slice/index.html index eb68df4907..b69293d1db 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/slice/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/slice/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>arr</var>.slice([<var>begin</var>[, <var>end</var>]])</pre> +<pre class="syntaxbox"><var>arr</var>.slice([<var>begin</var>[, <var>end</var>]])</pre> <h2 id="参数">参数</h2> @@ -63,7 +63,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice <h3 id="返回现有数组的一部分">返回现有数组的一部分</h3> -<pre class="brush: js notranslate">var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; +<pre class="brush: js">var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; var citrus = fruits.slice(1, 3); // fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'] @@ -78,7 +78,7 @@ var citrus = fruits.slice(1, 3); <p>在下例中, <code>slice</code> 从 <code>myCar</code> 中创建了一个新数组<code>newCar</code>。两个数组都包含了一个 <code>myHonda</code> 对象的引用。当 <code>myHonda</code> 的 <code>color</code> 属性改变为 <code>purple</code>,则两个数组中的对应元素都会随之改变。</p> -<pre class="brush: js notranslate">// 使用 slice 方法从 myCar 中创建一个 newCar。 +<pre class="brush: js">// 使用 slice 方法从 myCar 中创建一个 newCar。 var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } }; var myCar = [myHonda, 2, "cherry condition", "purchased 1997"]; var newCar = myCar.slice(0, 2); @@ -100,7 +100,7 @@ console.log('newCar[0].color = ' + newCar[0].color); <p>上述代码输出:</p> -<pre class="brush: js notranslate"> myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, +<pre class="brush: js"> myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2, 'cherry condition', 'purchased 1997'] newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2] myCar[0].color = red @@ -114,7 +114,7 @@ newCar[0].color = purple <p><code>slice</code> 方法可以用来将一个类数组(Array-like)对象/集合转换成一个新数组。你只需将该方法绑定到这个对象上。 一个函数中的 {{jsxref("Functions/arguments", "arguments")}} 就是一个类数组对象的例子。</p> -<pre class="brush: js notranslate">function list() { +<pre class="brush: js">function list() { return Array.prototype.slice.call(arguments); } @@ -123,7 +123,7 @@ var list1 = list(1, 2, 3); // [1, 2, 3] <p>除了使用 <code>Array.prototype.slice.call(</code><code>arguments</code><code>)</code>,你也可以简单的使用 <code>[].slice.call(arguments)</code> 来代替。另外,你可以使用 <code>bind</code> 来简化该过程。</p> -<pre class="brush: js notranslate">var unboundSlice = Array.prototype.slice; +<pre class="brush: js">var unboundSlice = Array.prototype.slice; var slice = Function.prototype.call.bind(unboundSlice); function list() { @@ -137,7 +137,7 @@ var list1 = list(1, 2, 3); // [1, 2, 3] <p>根据规范,使用 <code>Array.prototype.slice</code> 转换宿主对象(如 DOM 对象)时,不必遵循 Mozilla 的默认行为,即可以转化任何符合条件的伪数组宿主对象为数组,IE < 9 没有遵循,而 IE9 + 遵循这个行为,但是稍加改造可以使其在跨浏览器使用时更可靠。只要其他现代浏览器继续支持该行为,目前 IE 9+、FireFox、Chrome、Safari 以及 Opera 都支持,开发者在使用下面代码时遍历 DOM 时就不会被该方法的字面意义误导,即 IE < 9 不能转化 DOM Collections。开发者可以安全地根据语义知道该方法的实际上的标准行为。(下面的代码还修正了 IE 中 <code>slice()</code> 方法第二个参数不允许为显式的 {{jsxref("Global_Objects/null", "null")}}/{{jsxref("Global_Objects/undefined", "undefined")}} 值的问题,其他现代浏览器,包括 IE9+ 都允许)。</p> -<pre class="brush: js notranslate">/** +<pre class="brush: js">/** * Shim for "fixing" IE's lack of support (IE < 9) for applying slice * on host objects like NamedNodeMap, NodeList, and HTMLCollection * (technically, since host objects have been implementation-dependent, diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/values/index.html b/files/zh-cn/web/javascript/reference/global_objects/array/values/index.html index 7af8b40436..d8cc03f53f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/values/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/array/values/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/values <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>arr</var>.values()</pre> +<pre class="syntaxbox"><var>arr</var>.values()</pre> <h3 id="返回值">返回值</h3> @@ -30,7 +30,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/values <h3 id="使用_for...of_循环进行迭代">使用 <code>for...of</code> 循环进行迭代</h3> -<pre class="brush: js notranslate">let arr = ['w', 'y', 'k', 'o', 'p']; +<pre class="brush: js">let arr = ['w', 'y', 'k', 'o', 'p']; let eArr = arr.values(); for (let letter of eArr) { @@ -39,11 +39,11 @@ for (let letter of eArr) { <p><strong>Array.prototype.values</strong> 是 <strong>Array.prototype[Symbol.iterator] </strong>的默认实现。</p> -<pre class="notranslate">Array.prototype.values === Array.prototype[Symbol.iterator] // true </pre> +<pre>Array.prototype.values === Array.prototype[Symbol.iterator] // true </pre> <h3 id="使用_.next_迭代">使用 <code>.next()</code> 迭代</h3> -<pre class="notranslate">var arr = ['a', 'b', 'c', 'd', 'e']; +<pre>var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); iterator.next(); // Object { value: "a", done: false } iterator.next().value; // "b" @@ -59,7 +59,7 @@ iterator.next().value; // undefined</pre> <p>例子:</p> -<pre class="notranslate">var arr = ['a', 'b', 'c', 'd', 'e']; +<pre>var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); for (let letter of iterator) { console.log(letter); @@ -72,7 +72,7 @@ console.log(letter); <p><strong>值</strong>: 数组迭代器中存储的是原数组的地址,而不是数组元素值。</p> -<pre class="notranslate">var arr = ['a', 'b', 'c', 'd', 'e']; +<pre>var arr = ['a', 'b', 'c', 'd', 'e']; var iterator = arr.values(); console.log(iterator); // Array Iterator { } iterator.next().value; // "a" diff --git a/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/index.html b/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/index.html index 0dde8cd36a..f58f460328 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/index.html @@ -24,7 +24,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">new ArrayBuffer(length) +<pre class="syntaxbox">new ArrayBuffer(length) </pre> <h3 id="参数">参数</h3> @@ -104,7 +104,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer <p>下面的例子创建了一个 8 字节的缓冲区,并使用一个 {{jsxref("Global_Objects/Int32Array", "Int32Array")}} 来引用它:</p> -<pre class="notranslate"><code>var buffer = new ArrayBuffer(8); +<pre><code>var buffer = new ArrayBuffer(8); var view = new Int32Array(buffer);</code> </pre> @@ -143,11 +143,11 @@ var view = new Int32Array(buffer);</code> <p>从 ECMAScript 2015 开始,<code>ArrayBuffer</code> 对象需要用 {{jsxref("Operators/new", "new")}} 运算符创建。如果调用构造函数时没有使用 <code>new</code>,将会抛出 {{jsxref("TypeError")}} 异常。</p> -<pre class="brush: js example-bad notranslate">var dv = ArrayBuffer(10); +<pre class="brush: js example-bad">var dv = ArrayBuffer(10); // TypeError: calling a builtin ArrayBuffer constructor // without new is forbidden</pre> -<pre class="brush: js example-good notranslate">var dv = new ArrayBuffer(10);</pre> +<pre class="brush: js example-good">var dv = new ArrayBuffer(10);</pre> <h2 id="相关链接">相关链接</h2> diff --git a/files/zh-cn/web/javascript/reference/global_objects/atomics/index.html b/files/zh-cn/web/javascript/reference/global_objects/atomics/index.html index 838b6d8b99..2b3b3364a4 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/atomics/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/atomics/index.html @@ -54,7 +54,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Atomics <h3 id="使用_Atomics">使用 Atomics</h3> -<pre class="brush: js notranslate">const sab = new SharedArrayBuffer(1024); +<pre class="brush: js">const sab = new SharedArrayBuffer(1024); const ta = new Uint8Array(sab); ta[0]; @@ -101,19 +101,19 @@ Atomics.load(ta, 0); // 4 <p>给定一个共享的 <code>Int32Array</code>:</p> -<pre class="brush: js notranslate">const sab = new SharedArrayBuffer(1024); +<pre class="brush: js">const sab = new SharedArrayBuffer(1024); const int32 = new Int32Array(sab); </pre> <p>读取线程正在休眠并位置0上等待。只要该位置应为0,它就不会继续。但是,一旦写入线程存储了新值,写入线程将通知它并返回新值(123)。</p> -<pre class="brush: js notranslate">Atomics.wait(int32, 0, 0); +<pre class="brush: js">Atomics.wait(int32, 0, 0); console.log(int32[0]); // 123 </pre> <p>写入线程存储一个新值并再写入完成时通知等待线程:</p> -<pre class="brush: js notranslate">console.log(int32[0]); // 0; +<pre class="brush: js">console.log(int32[0]); // 0; Atomics.store(int32, 0, 123); Atomics.notify(int32, 0, 1);</pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/atomics/notify/index.html b/files/zh-cn/web/javascript/reference/global_objects/atomics/notify/index.html index bf2399192c..6459625463 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/atomics/notify/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/atomics/notify/index.html @@ -18,7 +18,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Atomics/notify <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">Atomics.notify(typedArray, index, count) +<pre class="syntaxbox">Atomics.notify(typedArray, index, count) </pre> <h3 id="参数">参数</h3> @@ -47,18 +47,18 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Atomics/notify <p>分配一个共享的 <code>Int32Array</code>:</p> -<pre class="brush: js notranslate">var sab = new SharedArrayBuffer(1024); +<pre class="brush: js">var sab = new SharedArrayBuffer(1024); var int32 = new Int32Array(sab); </pre> <p>一个读线程会进入休眠并监视索引0处的值(默认为0)。只要索引0处的值不为0,读进程就会唤醒。但是,一旦写进程存储了一个新的值,写进程就会产生一个提醒并返回写入后的新值(123)。(这里示例有问题或者说对初学者不友好,如果直接在浏览器控制台运行下面代码会报错,因为我们不能尝试睡眠主线程,可以见 <a href="https://github.com/lizhongzhen11/lizz-blog/issues/125#notice">重学js —— 结构化数据之Atomics对象</a>,同时我在 <strong>codepen </strong>写了一个示例:<a href="https://codepen.io/lizhongzhen11/project/editor/AmzyaY#">Atomics.wait使用示例</a>)</p> -<pre class="brush: js notranslate">Atomics.wait(int32, 0, 0); +<pre class="brush: js">Atomics.wait(int32, 0, 0); console.log(int32[0]); // 123</pre> <p>写进程写入一个新值并告知等待进程已经写入成功了:</p> -<pre class="brush: js notranslate">console.log(int32[0]); // 0; +<pre class="brush: js">console.log(int32[0]); // 0; Atomics.store(int32, 0, 123); Atomics.notify(int32, 0, 1);</pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/bigint64array/index.html b/files/zh-cn/web/javascript/reference/global_objects/bigint64array/index.html index 69b980e18b..23361908f2 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/bigint64array/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/bigint64array/index.html @@ -111,7 +111,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/BigInt64Array <h3 id="不同的方法去创建一个_BigInt64Array">不同的方法去创建一个 <code>BigInt64Array</code></h3> -<pre class="brush: js notranslate">// From a length +<pre class="brush: js">// From a length var bigint64 = new BigInt64Array(2); bigint64[0] = 42n; console.log(bigint64[0]); // 42n diff --git a/files/zh-cn/web/javascript/reference/global_objects/boolean/index.html b/files/zh-cn/web/javascript/reference/global_objects/boolean/index.html index a236f20273..4101843056 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/boolean/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/boolean/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Boolean <p>其值不是{{jsxref("undefined")}}或{{jsxref("null")}}的任何对象(包括其值为<code>false</code>的布尔对象)在传递给条件语句时都将计算为<code>true</code>。 例如,以下{{jsxref("Statements/if...else", "if")}}语句中的条件评估为<code>true</code>:</p> -<pre class="brush: js notranslate">var x = new Boolean(false); +<pre class="brush: js">var x = new Boolean(false); if (x) { // 这里的代码会被执行 } @@ -27,7 +27,7 @@ if (x) { <p>基本类型的布尔值不受此规则影响。例如下面的 {{jsxref("Statements/if...else", "if")}} 语句的条件为假:</p> -<pre class="brush: js notranslate">var x = false; +<pre class="brush: js">var x = false; if (x) { // 这里的代码不会执行 } @@ -35,14 +35,14 @@ if (x) { <p>不要用创建 <code>Boolean</code> 对象的方式将一个非布尔值转化成布尔值,直接将 <code>Boolean</code> 当做转换函数来使用即可,或者使用<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Logical_Operators#%E9%80%BB%E8%BE%91%E9%9D%9E%EF%BC%88!%EF%BC%89">双重非(!!)运算符</a>:</p> -<pre class="brush: js notranslate">var x = Boolean(expression); // 推荐 +<pre class="brush: js">var x = Boolean(expression); // 推荐 var x = !!(expression); // 推荐 var x = new Boolean(expression); // 不太好 </pre> <p>对于任何对象,即使是值为 <code>false</code> 的 <code>Boolean</code> 对象,当将其传给 <code>Boolean</code> 函数时,生成的 <code>Boolean</code> 对象的值都是 <code>true</code>。</p> -<pre class="brush: js notranslate">var myFalse = new Boolean(false); // true +<pre class="brush: js">var myFalse = new Boolean(false); // true var g = new Boolean(myFalse); // true var myString = new String("Hello"); var s = new Boolean(myString); // true @@ -74,7 +74,7 @@ var s = new Boolean(myString); // true <h3 id="创建值为_false_的_Boolean_对象">创建值为 <code>false</code> 的 <code>Boolean</code> 对象</h3> -<pre class="brush: js notranslate">var bNoParam = new Boolean(); +<pre class="brush: js">var bNoParam = new Boolean(); var bZero = new Boolean(0); var bNull = new Boolean(null); var bEmptyString = new Boolean(''); @@ -83,7 +83,7 @@ var bfalse = new Boolean(false); <h3 id="创建值为_true_的_Boolean_对象">创建值为 <code>true</code> 的 <code>Boolean</code> 对象</h3> -<pre class="brush: js notranslate">var btrue = new Boolean(true); +<pre class="brush: js">var btrue = new Boolean(true); var btrueString = new Boolean('true'); var bfalseString = new Boolean('false'); var bSuLin = new Boolean('Su Lin'); diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/index.html b/files/zh-cn/web/javascript/reference/global_objects/date/index.html index 152caed1a0..2c8e41406b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/date/index.html @@ -18,7 +18,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Date <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">new Date(); +<pre class="syntaxbox">new Date(); new Date(<var>value</var>); new Date(<var>dateString</var>); new Date(<var>year</var>, <var>monthIndex</var> [, <var>day</var> [, <var>hours</var> [, <var>minutes</var> [, <var>seconds</var> [, <var>milliseconds</var>]]]]]);</pre> @@ -147,7 +147,7 @@ new Date(<var>year</var>, <var>monthIndex</var> [, <var>day</var> [, <var>hours< <p><strong>注意:</strong> 由于浏览器差异和不一致性,强烈建议不要使用<code>Date</code>构造函数(和<code>Date.parse</code>,它们是等效的)解析日期字符串。</p> </div> -<pre class="brush: js notranslate">var today = new Date(); +<pre class="brush: js">var today = new Date(); var birthday = new Date('December 17, 1995 03:24:00'); var birthday = new Date('1995-12-17T03:24:00'); var birthday = new Date(1995, 11, 17); @@ -158,7 +158,7 @@ var birthday = new Date(1995, 11, 17, 3, 24, 0); <p>为了创建和获取 0 到 99 之间的年份,应使用 {{jsxref("Date.prototype.setFullYear()")}} 和 {{jsxref("Date.prototype.getFullYear()")}} 方法。</p> -<pre class="brush: js notranslate">var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) +<pre class="brush: js">var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) // 已弃用的方法, 同样将 98 映射为 1998 date.setYear(98); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) @@ -172,7 +172,7 @@ date.setFullYear(98); // Sat Feb 01 0098 00:00:00 GMT+0000 (BST) <p>由于不同日期、月份、年份长度的不同(日期长度不同来自夏令时的切换),使用大于秒、分钟、小时的单位表示经过的时间会遇到很多问题,在使用前需要经过详尽的调研。</p> -<pre class="brush: js notranslate">// 使用 Date 对象 +<pre class="brush: js">// 使用 Date 对象 var start = Date.now(); // 调用一个消耗一定时间的方法: @@ -180,7 +180,7 @@ doSomethingForALongTime(); var end = Date.now(); var elapsed = end - start; // 以毫秒计的运行时长</pre> -<pre class="brush: js notranslate">// 使用内建的创建方法 +<pre class="brush: js">// 使用内建的创建方法 var start = new Date(); // 调用一个消耗一定时间的方法: @@ -188,7 +188,7 @@ doSomethingForALongTime(); var end = new Date(); var elapsed = end.getTime() - start.getTime(); // 运行时间的毫秒值</pre> -<pre class="brush: js notranslate" dir="ltr">// to test a function and get back its return +<pre class="brush: js" dir="ltr">// to test a function and get back its return function printElapsedTime (fTest) { var nStartTime = Date.now(), vReturn = fTest(), @@ -205,7 +205,7 @@ yourFunctionReturn = printElapsedTime(yourFunction); <h3 id="获取自_Unix_起始时间以来经过的秒数">获取自 Unix 起始时间以来经过的秒数</h3> -<pre class="brush: js notranslate">var seconds = Math.floor(Date.now() / 1000);</pre> +<pre class="brush: js">var seconds = Math.floor(Date.now() / 1000);</pre> <p>注意此处需要返回一个整数 (仅做除法得到的不是整数),并且需要返回实际已经经过的秒数(所以这里使用了{{jsxref("Math.floor()")}}而不是{{jsxref("Math.round()")}}).</p> diff --git a/files/zh-cn/web/javascript/reference/global_objects/encodeuricomponent/index.html b/files/zh-cn/web/javascript/reference/global_objects/encodeuricomponent/index.html index dd30f152b1..2864496ff8 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/encodeuricomponent/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/encodeuricomponent/index.html @@ -15,7 +15,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">encodeURIComponent(str);</pre> +<pre class="syntaxbox">encodeURIComponent(str);</pre> <h3 id="参数">参数</h3> @@ -32,7 +32,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent <p><code>encodeURIComponent</code> 转义除了如下所示外的所有字符:</p> -<pre class="notranslate">不转义的字符: +<pre>不转义的字符: A-Z a-z 0-9 <code>-</code> <code>_</code> <code>.</code> <code>!</code> <code>~</code> <code>*</code> <code>'</code> <code>(</code> <code>)</code></pre> <p><code>encodeURIComponent()</code> 和 <strong><code>encodeURI</code></strong> 有以下几个不同点:</p> @@ -54,7 +54,7 @@ console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encode <p>注意,如果试图编码一个非高-低位完整的代理字符,将会抛出一个 {{jsxref("URIError")}} 错误,例如:</p> -<pre class="brush: js notranslate">// 高低位完整 +<pre class="brush: js">// 高低位完整 alert(encodeURIComponent('\uD800\uDFFF')); // 只有高位,将抛出"URIError: malformed URI sequence" @@ -69,7 +69,7 @@ alert(encodeURIComponent('\uDFFF')); </pre> <p>为了更严格的遵循 {{rfc("3986")}}(它保留 !, ', (, ), 和 *),即使这些字符并没有正式划定 URI 的用途,下面这种方式是比较安全的:</p> -<pre class="brush: js notranslate">function fixedEncodeURIComponent (str) { +<pre class="brush: js">function fixedEncodeURIComponent (str) { return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { return '%' + c.charCodeAt(0).toString(16).toUpperCase(); }); @@ -79,7 +79,7 @@ alert(encodeURIComponent('\uDFFF')); </pre> <p>下面这个例子提供了 UTF-8 下 {{HTTPHeader("Content-Disposition")}} 和 {{HTTPHeader("Link")}} 的服务器响应头信息的参数(例如 UTF-8 文件名):</p> -<pre class="brush: js notranslate">var fileName = 'my file(2).txt'; +<pre class="brush: js">var fileName = 'my file(2).txt'; var header = "Content-Disposition: attachment; filename*=UTF-8''" + encodeRFC5987ValueChars(fileName); diff --git a/files/zh-cn/web/javascript/reference/global_objects/finalizationregistry/index.html b/files/zh-cn/web/javascript/reference/global_objects/finalizationregistry/index.html index 10e720eb80..5dbd569caf 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/finalizationregistry/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/finalizationregistry/index.html @@ -21,14 +21,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry <p>你在回调中创建了如下的 registry:</p> -<pre class="brush: js notranslate">const registry = new FinalizationRegistry(heldValue => { +<pre class="brush: js">const registry = new FinalizationRegistry(heldValue => { // .... }); </pre> <p>然后,你可以通过调用`register`方法,注册任何你想要清理回调的对象,传入该对象和*所含的值*。</p> -<pre class="brush: js notranslate">registry.register(theObject, "some value"); +<pre class="brush: js">registry.register(theObject, "some value"); </pre> <p>The registry does not keep a strong reference to the object, as that would defeat the purpose (if the registry held it strongly, the object would never be reclaimed).</p> @@ -39,14 +39,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry <p>It's common to use the object itself as the unregister token, which is just fine:</p> -<pre class="brush: js notranslate">registry.register(theObject, "some value", theObject); +<pre class="brush: js">registry.register(theObject, "some value", theObject); // ...some time later, if you don't care about `theObject` anymore... registry.unregister(theObject); </pre> <p>It doesn't have to be the same object, though; it can be a different one:</p> -<pre class="brush: js notranslate">registry.register(theObject, "some value", tokenObject); +<pre class="brush: js">registry.register(theObject, "some value", tokenObject); // ...some time later, if you don't care about `theObject` anymore... registry.unregister(tokenObject); </pre> @@ -108,7 +108,7 @@ registry.unregister(tokenObject); <p>You create the registry passing in the callback:</p> -<pre class="brush: js notranslate">const registry = new FinalizationRegistry(heldValue => { +<pre class="brush: js">const registry = new FinalizationRegistry(heldValue => { // .... }); </pre> @@ -117,7 +117,7 @@ registry.unregister(tokenObject); <p>Then you register any objects you want a cleanup callback for by calling the `register` method, passing in the object and a *held value* for it:</p> -<pre class="brush: js notranslate">registry.register(theObject, "some value");</pre> +<pre class="brush: js">registry.register(theObject, "some value");</pre> <h2 id="Specifications">Specifications</h2> diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/apply/index.html b/files/zh-cn/web/javascript/reference/global_objects/function/apply/index.html index d345215619..944791e29c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/apply/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/function/apply/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code><em>func</em>.apply(<em>thisArg</em><em>, [</em><em>argsArray</em>])</code></pre> +<pre class="syntaxbox"><code><em>func</em>.apply(<em>thisArg</em><em>, [</em><em>argsArray</em>])</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -58,7 +58,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply <p><code>apply</code>正派上用场!</p> -<pre class="brush: js notranslate">var array = ['a', 'b']; +<pre class="brush: js">var array = ['a', 'b']; var elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2] @@ -70,7 +70,7 @@ console.info(array); // ["a", "b", 0, 1, 2] <p>下面是示例,我们将用<code>Math.max</code>/<code>Math.min</code>求得数组中的最大/小值。</p> -<pre class="brush: js notranslate">/* 找出数组中最大/小的数字 */ +<pre class="brush: js">/* 找出数组中最大/小的数字 */ var numbers = [5, 6, 2, 3, 7]; /* 使用Math.min/Math.max以及apply 函数时的代码 */ @@ -91,7 +91,7 @@ for (var i = 0; i < numbers.length; i++) { <p>如果你的参数数组可能非常大,那么推荐使用下面这种混合策略:将数组切块后循环传入目标方法:</p> -<pre class="brush: js notranslate">function minOfArray(arr) { +<pre class="brush: js">function minOfArray(arr) { var min = Infinity; var QUANTUM = 32768; @@ -110,7 +110,7 @@ var min = minOfArray([5, 6, 2, 3, 7]); <p>你可以使用apply来链接一个对象<a href="/zh-CN/docs/JavaScript/Reference/Operators/new" title="JavaScript/Reference/Operators/new">构造器</a>,类似于Java。在接下来的例子中我们会创建一个全局<a href="/zh-CN/docs/JavaScript/Reference/Global_Objects/Function" title="JavaScript/Reference/Global_Objects/Function"><code>Function</code></a> 对象的construct方法 ,来使你能够在构造器中使用一个类数组对象而非参数列表。</p> -<pre class="brush: js notranslate">Function.prototype.construct = function (aArgs) { +<pre class="brush: js">Function.prototype.construct = function (aArgs) { var oNew = Object.create(this.prototype); this.apply(oNew, aArgs); return oNew; @@ -122,7 +122,7 @@ var min = minOfArray([5, 6, 2, 3, 7]); <p>Using {{jsxref("Object/__proto__", "Object.__proto__")}}:</p> -<pre class="brush: js notranslate">Function.prototype.construct = function (aArgs) { +<pre class="brush: js">Function.prototype.construct = function (aArgs) { var oNew = {}; oNew.__proto__ = this.prototype; this.apply(oNew, aArgs); @@ -131,7 +131,7 @@ var min = minOfArray([5, 6, 2, 3, 7]); <p>使用闭包:</p> -<pre class="brush: js notranslate" style="font-style: normal;">Function.prototype.construct = function(aArgs) { +<pre class="brush: js" style="font-style: normal;">Function.prototype.construct = function(aArgs) { var fConstructor = this, fNewConstr = function() { fConstructor.apply(this, aArgs); }; @@ -141,7 +141,7 @@ var min = minOfArray([5, 6, 2, 3, 7]); <p class="brush: js" style="font-style: normal;">使用 Function 构造器:</p> -<pre class="brush: js notranslate">Function.prototype.construct = function (aArgs) { +<pre class="brush: js">Function.prototype.construct = function (aArgs) { var fNewConstr = new Function(""); fNewConstr.prototype = this.prototype; var oNew = new fNewConstr(); @@ -152,7 +152,7 @@ var min = minOfArray([5, 6, 2, 3, 7]); <p>使用示例:</p> -<pre class="brush: js notranslate">function MyConstructor (arguments) { +<pre class="brush: js">function MyConstructor (arguments) { for (var nProp = 0; nProp < arguments.length; nProp++) { this["property" + nProp] = arguments[nProp]; } diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/bind/index.html b/files/zh-cn/web/javascript/reference/global_objects/function/bind/index.html index c612abb1df..8940da5ad4 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/bind/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/function/bind/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>function</var></code>.bind(<var>thisArg</var>[, <var>arg1</var>[, <var>arg2</var>[, ...]]])</pre> +<pre class="syntaxbox"><code><var>function</var></code>.bind(<var>thisArg</var>[, <var>arg1</var>[, <var>arg2</var>[, ...]]])</pre> <h3 id="参数">参数</h3> @@ -63,7 +63,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind <p><code>bind()</code> 最简单的用法是创建一个函数,不论怎么调用,这个函数都有同样的 <strong><code>this</code></strong> 值。JavaScript新手经常犯的一个错误是将一个方法从对象中拿出来,然后再调用,期望方法中的 <code>this</code> 是原来的对象(比如在回调中传入这个方法)。如果不做特殊处理的话,一般会丢失原来的对象。基于这个函数,用原始的对象创建一个绑定函数,巧妙地解决了这个问题:</p> -<pre class="brush: js notranslate">this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象 +<pre class="brush: js">this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象 var module = { x: 81, getX: function() { return this.x; } @@ -85,7 +85,7 @@ boundGetX(); // 81 <p><code>bind()</code> 的另一个最简单的用法是使一个函数拥有预设的初始参数。只要将这些参数(如果有的话)作为 <code>bind()</code> 的参数写在 <code>this</code> 后面。当绑定函数被调用时,这些参数会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们后面。</p> -<pre class="brush: js notranslate">function list() { +<pre class="brush: js">function list() { return Array.prototype.slice.call(arguments); } @@ -120,7 +120,7 @@ var result3 = addThirtySeven(5, 10); <p>在默认情况下,使用 {{ domxref("window.setTimeout()") }} 时,<code>this</code> 关键字会指向 {{ domxref("window") }} (或 <code>global</code>)对象。当类的方法中需要 <code>this</code> 指向类的实例时,你可能需要显式地把 <code>this</code> 绑定到回调函数,就不会丢失该实例的引用。</p> -<pre class="brush: js notranslate"><code>function LateBloomer() { +<pre class="brush: js"><code>function LateBloomer() { this.petalCount = Math.ceil(Math.random() * 12) + 1; } @@ -145,7 +145,7 @@ flower.bloom(); // 一秒钟后, 调用 'declare' 方法</code></pre> <p>绑定函数自动适应于使用 {{jsxref("Operators/new", "new")}} 操作符去构造一个由目标函数创建的新实例。当一个绑定函数是用来构建一个值的,原来提供的 <code>this</code> 就会被忽略。不过提供的参数列表仍然会插入到构造函数调用时的参数列表之前。</p> -<pre class="brush: js notranslate">function Point(x, y) { +<pre class="brush: js">function Point(x, y) { this.x = x; this.y = y; } @@ -178,7 +178,7 @@ new YAxisPoint(17, 42) instanceof Point; // true</pre> <p>请注意,你不需要做特别的处理就可以创建一个和 {{jsxref("Operators/new", "new")}} 操作符一起使用的绑定函数。也就是说,你不需要做特别处理就可以创建一个可以被直接调用的绑定函数,即使你更希望绑定函数是用 {{jsxref("Operators/new", "new")}} 操作符来调用。</p> -<pre class="brush: js notranslate">// ...接着上面的代码继续的话, +<pre class="brush: js">// ...接着上面的代码继续的话, // 这个例子可以直接在你的 JavaScript 控制台运行 // 仍然能作为一个普通函数来调用 @@ -196,7 +196,7 @@ emptyObj.x + ',' + emptyObj.y; // '0,13' <p>你可以用 {{jsxref("Array.prototype.slice")}} 来将一个类似于数组的对象(array-like object)转换成一个真正的数组,就拿它来举例子吧。你可以简单地这样写:</p> -<pre class="brush: js notranslate">var slice = Array.prototype.slice; +<pre class="brush: js">var slice = Array.prototype.slice; // ... @@ -204,7 +204,7 @@ slice.apply(arguments);</pre> <p>用 <code>bind()</code>可以使这个过程变得简单。在下面这段代码里面,<code>slice</code> 是 {{jsxref("Function.prototype")}} 的 {{jsxref("Function.prototype.apply()", "apply()")}} 方法的绑定函数,并且将 {{jsxref("Array.prototype")}} 的 {{jsxref("Array.prototype.slice()", "slice()")}} 方法作为 <strong><code>this</code></strong> 的值。这意味着我们压根儿用不着上面那个 <code>apply()</code>调用了。</p> -<pre class="brush: js notranslate">// 与前一段代码的 "slice" 效果相同 +<pre class="brush: js">// 与前一段代码的 "slice" 效果相同 var unboundSlice = Array.prototype.slice; var slice = Function.prototype.apply.bind(unboundSlice); diff --git a/files/zh-cn/web/javascript/reference/global_objects/globalthis/index.html b/files/zh-cn/web/javascript/reference/global_objects/globalthis/index.html index e3c5d1b0a2..a4dc9510c1 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/globalthis/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/globalthis/index.html @@ -24,7 +24,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/globalThis <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">globalThis</pre> +<pre class="syntaxbox">globalThis</pre> <h2 id="描述">描述</h2> @@ -46,7 +46,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/globalThis <p>在 <code>globalThis</code> 之前,获取某个全局对象的唯一方式就是 <code>Function('return this')()</code>,但是这在某些情况下会违反 <a href="/zh-CN/docs/Web/HTTP/CSP">CSP</a> 规则,所以,<a href="https://github.com/paulmillr/es6-shim">es6-shim</a> 使用了类似如下的方式:</p> -<pre class="brush: js notranslate">var getGlobal = function () { +<pre class="brush: js">var getGlobal = function () { if (typeof self !== 'undefined') { return self; } if (typeof window !== 'undefined') { return window; } if (typeof global !== 'undefined') { return global; } @@ -62,7 +62,7 @@ if (typeof globals.setTimeout !== 'function') { <p>但是有了 <code>globalThis</code> 之后,只需要:</p> -<pre class="brush: js notranslate">if (typeof globalThis.setTimeout !== 'function') { +<pre class="brush: js">if (typeof globalThis.setTimeout !== 'function') { // 此环境中没有 setTimeout 方法! }</pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/infinity/index.html b/files/zh-cn/web/javascript/reference/global_objects/infinity/index.html index 3181d4b7ff..f20755f907 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/infinity/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/infinity/index.html @@ -25,7 +25,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Infinity <h2 id="示例">示例</h2> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">console.log(Infinity ); /* Infinity */ +<pre class="brush: js line-numbers language-js"><code class="language-js">console.log(Infinity ); /* Infinity */ console.log(Infinity + 1 ); /* Infinity */ console.log(Math.pow(10, 1000)); /* Infinity */ console.log(Math.log(0) ); /* -Infinity */ diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/locale/index.html b/files/zh-cn/web/javascript/reference/global_objects/intl/locale/index.html index 181d9dc0bf..08af53d8fa 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/locale/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/locale/index.html @@ -64,13 +64,13 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Intl/Locale <p>很简单,就是需要给{{jsxref("Locale/Locale", "Intl.Locale")}} 构造函数传入一个 locale 标识字符串作为参数:</p> -<pre class="brush: js notranslate">let us = new Intl.Locale('zh-Hans-CN');</pre> +<pre class="brush: js">let us = new Intl.Locale('zh-Hans-CN');</pre> <h3 id="使用配置实例化">使用配置实例化</h3> <p>构造函数支持传入 object 作为配置,object 中可包含多个配置属性。例如,设置 <code><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle">hourCycle</a></code> 属性,用于设置您所需要的小时周期类型:</p> -<pre class="brush: js notranslate">let zh12hour = new Intl.Locale("zh-Hans-CN", {hourCycle: "h12"}); +<pre class="brush: js">let zh12hour = new Intl.Locale("zh-Hans-CN", {hourCycle: "h12"}); console.log(zh12hour.hourCycle); // Prints "h12"</pre> <h2 id="规范">规范</h2> diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/relativetimeformat/index.html b/files/zh-cn/web/javascript/reference/global_objects/intl/relativetimeformat/index.html index 561af8a1fe..a05c3385dd 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/relativetimeformat/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/relativetimeformat/index.html @@ -14,7 +14,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat <h2 id="句法">句法</h2> -<pre class="notranslate"><code>new Intl.RelativeTimeFormat([<var>locales</var>[, <var>options</var>]]) +<pre><code>new Intl.RelativeTimeFormat([<var>locales</var>[, <var>options</var>]]) </code></pre> <h3 id="参数">参数</h3> @@ -84,7 +84,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat <p>以下示例显示如何使用英语创建相对时间格式化程序。</p> -<pre class="brush: js notranslate">//在语言环境中创建相对时间格式化程序 +<pre class="brush: js">//在语言环境中创建相对时间格式化程序 //显式传入默认值。 const rtf = new Intl.RelativeTimeFormat("en",{ localeMatcher: "bestfit",//其他值:"lookup" @@ -104,7 +104,7 @@ rtf.format(1,"day"); <p>如果<code>numeric:auto</code>选项被传递,它将生成字符串<code>yesterday</code>或<code>tomorrow</code>代替<code>1 day ago</code>或<code>in 1 day</code>。这允许不必总是在输出中使用数值。</p> -<pre class="brush: js notranslate">//在语言环境中创建相对时间格式化程序 +<pre class="brush: js">//在语言环境中创建相对时间格式化程序 //使用数字:传入"auto"选项值。 const rtf = new Intl.RelativeTimeFormat("en",{numeric: "auto"}); @@ -121,7 +121,7 @@ rtf.format(1,"day"); <p>以下示例显示如何创建返回格式化部件的相对时间格式器</p> -<pre class="brush: js notranslate">const rtf = new Intl.RelativeTimeFormat("en",{numeric: "auto"}); +<pre class="brush: js">const rtf = new Intl.RelativeTimeFormat("en",{numeric: "auto"}); //使用日期单位格式化相对时间。 rtf.formatToParts(-1,"day"); diff --git a/files/zh-cn/web/javascript/reference/global_objects/json/stringify/index.html b/files/zh-cn/web/javascript/reference/global_objects/json/stringify/index.html index 3ccfd067d3..ac4e1cdd67 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/json/stringify/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/json/stringify/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code>JSON.stringify(<em>value</em>[, <em>replacer</em> [, <em>space</em>]])</code> +<pre class="syntaxbox"><code>JSON.stringify(<em>value</em>[, <em>replacer</em> [, <em>space</em>]])</code> </pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -64,7 +64,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify <h3 id="使用_JSON.stringify">使用 JSON.stringify</h3> -<pre class="brush: js notranslate">JSON.stringify({}); // '{}' +<pre class="brush: js">JSON.stringify({}); // '{}' JSON.stringify(true); // 'true' JSON.stringify("foo"); // '"foo"' JSON.stringify([1, "false", false]); // '[1,"false",false]' @@ -134,7 +134,7 @@ JSON.stringify( <h4 id="例子function">例子(function)</h4> -<pre class="notranslate"><code>function replacer(key, value) { +<pre><code>function replacer(key, value) { if (typeof value === "string") { return undefined; } @@ -150,18 +150,18 @@ var jsonString = JSON.stringify(foo, replacer);</code></pre> <p>如果 <code>replacer</code> 是一个数组,数组的值代表将被序列化成 JSON 字符串的属性名。</p> -<pre class="notranslate"><code>JSON.stringify(foo, ['week', 'month']); +<pre><code>JSON.stringify(foo, ['week', 'month']); // '{"week":45,"month":7}', 只保留 “week” 和 “month” 属性值。</code></pre> <h3 id="space_参数"><code>space</code> 参数</h3> <p><code>space </code>参数用来控制结果字符串里面的间距。如果是一个数字, 则在字符串化时每一级别会比上一级别缩进多这个数字值的空格(最多10个空格);如果是一个字符串,则每一级别会比上一级别多缩进该字符串(或该字符串的前10个字符)。</p> -<pre class="brush: js notranslate">JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}'</pre> +<pre class="brush: js">JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}'</pre> <p>使用制表符(\t)来缩进:</p> -<pre class="brush: js notranslate">JSON.stringify({ uno: 1, dos : 2 }, null, '\t') +<pre class="brush: js">JSON.stringify({ uno: 1, dos : 2 }, null, '\t') // '{ \ // "uno": 1, \ // "dos": 2 \ @@ -172,7 +172,7 @@ var jsonString = JSON.stringify(foo, replacer);</code></pre> <p>如果一个被序列化的对象拥有 <code>toJSON</code> 方法,那么该 <code>toJSON</code> 方法就会覆盖该对象默认的序列化行为:不是该对象被序列化,而是调用 <code>toJSON</code> 方法后的返回值会被序列化,例如:</p> -<pre class="brush: js notranslate">var obj = { +<pre class="brush: js">var obj = { foo: 'foo', toJSON: function () { return 'bar'; @@ -186,7 +186,7 @@ JSON.stringify({x: obj}); // <code>'{"x":"bar"}'</code> <p>注意 JSON 不是 JavaScript 严格意义上的子集,在 JSON 中不需要省略两条终线(Line separator 和 Paragraph separator),但在 JavaScript 中需要被省略。因此,如果 JSON 被用作 JSONP 时,下面方法可以使用:</p> -<pre class="notranslate"><code>function jsFriendlyJSONStringify (s) { +<pre><code>function jsFriendlyJSONStringify (s) { return JSON.stringify(s). replace(/\u2028/g, '\\u2028'). replace(/\u2029/g, '\\u2029'); @@ -213,7 +213,7 @@ alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"}</code></pre> <p>一些时候,你想存储用户创建的一个对象,并且,即使在浏览器被关闭后仍能恢复该对象。下面的例子是 <code>JSON.stringify</code> 适用于这种情形的一个样板:</p> -<pre class="brush: js notranslate">// 创建一个示例数据 +<pre class="brush: js">// 创建一个示例数据 var session = { 'screens' : [], 'state' : true diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.html index 76ef36556e..50b701e541 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.html @@ -22,7 +22,7 @@ browser-compat: javascript.builtins.Map.forEach <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>myMap</var>.forEach(<var>callback([<var>value</var>][,<var>key</var>][,<var>map</var>])[, <var>thisArg</var>])</var></code></pre> +<pre class="syntaxbox"><code><var>myMap</var>.forEach(<var>callback([<var>value</var>][,<var>key</var>][,<var>map</var>])[, <var>thisArg</var>])</var></code></pre> <h3 id="参数">参数</h3> @@ -72,7 +72,7 @@ browser-compat: javascript.builtins.Map.forEach <p>以下的代码在每行中打印一个 <code>Map</code> 对象中的元素</p> -<pre class="brush:js notranslate">function logMapElements(value, key, map) { +<pre class="brush:js">function logMapElements(value, key, map) { console.log(`map.get('${key}') = ${value}`) } new Map([['foo', 3], ['bar', {}], ['baz', undefined]]).forEach(logMapElements) diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/keys/index.html b/files/zh-cn/web/javascript/reference/global_objects/map/keys/index.html index 59c1b50654..87758cf8f3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/keys/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/map/keys/index.html @@ -22,7 +22,7 @@ browser-compat: javascript.builtins.Map.keys <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><em>myMap</em>.keys()</code></pre> +<pre class="syntaxbox"><code><em>myMap</em>.keys()</code></pre> <h3 id="返回值">返回值</h3> @@ -32,7 +32,7 @@ browser-compat: javascript.builtins.Map.keys <h3 id="使用_keys">使用 <code>keys()</code></h3> -<pre class="brush:js notranslate">var myMap = new Map(); +<pre class="brush:js">var myMap = new Map(); myMap.set("0", "foo"); myMap.set(1, "bar"); myMap.set({}, "baz"); diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/floor/index.html b/files/zh-cn/web/javascript/reference/global_objects/math/floor/index.html index 530f15a033..6a8bb13fc2 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/floor/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/math/floor/index.html @@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code>Math.floor(<em>x</em>) </code></pre> +<pre class="syntaxbox"><code>Math.floor(<em>x</em>) </code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -39,7 +39,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor <h3 id="Example_Using_Math.floor" name="Example:_Using_Math.floor">例子:使用 <code>Math.floor</code></h3> -<pre class="brush:js notranslate">Math.floor( 45.95); +<pre class="brush:js">Math.floor( 45.95); // 45 Math.floor( 45.05); // 45 @@ -54,7 +54,7 @@ Math.floor(-45.95); <h3 id="Example_Decimal_adjustment" name="Example:_Decimal_adjustment">例子:十进制调整</h3> -<pre class="brush:js notranslate">// Closure +<pre class="brush:js">// Closure (function(){ /** diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/random/index.html b/files/zh-cn/web/javascript/reference/global_objects/math/random/index.html index e25608ec05..91796ae506 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/random/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/math/random/index.html @@ -21,7 +21,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code>Math.random()</code></pre> +<pre class="syntaxbox"><code>Math.random()</code></pre> <h3 id="Parameters" name="Parameters">返回值</h3> @@ -33,7 +33,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random <h3 id="得到一个大于等于0,小于1之间的随机数">得到一个大于等于0,小于1之间的随机数</h3> -<pre class="brush: js notranslate">function getRandom() { +<pre class="brush: js">function getRandom() { return Math.random(); }</pre> @@ -41,7 +41,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random <p>这个例子返回了一个在指定值之间的随机数。这个值不小于 <code>min</code>(有可能等于),并且小于(不等于)<code>max</code>。</p> -<pre class="brush: js notranslate">function getRandomArbitrary(min, max) { +<pre class="brush: js">function getRandomArbitrary(min, max) { return Math.random() * (max - min) + min; } </pre> @@ -50,7 +50,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random <p>这个例子返回了一个在指定值之间的随机整数。这个值不小于 <code>min</code> (如果 <code>min</code> 不是整数,则不小于 <code>min</code> 的向上取整数),且小于(不等于)<code>max</code>。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">function getRandomInt(min, max) { +<pre class="brush: js line-numbers language-js"><code class="language-js">function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min)) + min; </code>//不含最大值,含最小值<code class="language-js"> @@ -64,7 +64,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random <p>上一个例子提到的函数 <code>getRandomInt()</code> 结果范围包含了最小值,但不含最大值。如果你的随机结果需要同时包含最小值和最大值,怎么办呢? <code>getRandomIntInclusive()</code> 函数可以实现。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">function getRandomIntInclusive(min, max) { +<pre class="brush: js line-numbers language-js"><code class="language-js">function getRandomIntInclusive(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; //含最大值,含最小值 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/sin/index.html b/files/zh-cn/web/javascript/reference/global_objects/math/sin/index.html index 989c5af7e5..a08cda8912 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/sin/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/math/sin/index.html @@ -11,7 +11,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/sin <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate">Math.sin(<em>x</em>)</pre> +<pre class="syntaxbox">Math.sin(<em>x</em>)</pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -30,7 +30,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/sin <h3 id="Example_Using_Math.sin" name="Example:_Using_Math.sin">例子:使用 <code>Math.sin</code></h3> -<pre class="brush:js notranslate">Math.sin(0); // 0 +<pre class="brush:js">Math.sin(0); // 0 Math.sin(1); // 0.8414709848078965 Math.sin(Math.PI / 2); // 1</pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/sinh/index.html b/files/zh-cn/web/javascript/reference/global_objects/math/sinh/index.html index c9f0d376f9..1682a0ba73 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/sinh/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/math/sinh/index.html @@ -11,7 +11,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/sinh <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate">Math.sinh(<em>x</em>)</pre> +<pre class="syntaxbox">Math.sinh(<em>x</em>)</pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -28,7 +28,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/sinh <h2 id="Examples" name="Examples">示例</h2> -<pre class="brush:js notranslate">Math.sinh(0) // 0 +<pre class="brush:js">Math.sinh(0) // 0 Math.sinh(1) // 1.1752011936438014 Math.sinh("-1") // -1.1752011936438014 Math.sinh("foo") // NaN @@ -55,7 +55,7 @@ Math.sinh("foo") // NaN <p>该函数可以使用 {{jsxref("Math.exp()")}}<code> 函数来实现</code>:</p> -<pre class="brush: js language-js notranslate">function sinh(x){ +<pre class="brush: js language-js">function sinh(x){ return (Math.exp(x) - Math.exp(-x)) / 2; }</pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/isfinite/index.html b/files/zh-cn/web/javascript/reference/global_objects/number/isfinite/index.html index aef163cfb6..47a2ee8f0b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/isfinite/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/number/isfinite/index.html @@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code>Number.isFinite(v<var>alue</var>)</code></pre> +<pre class="syntaxbox"><code>Number.isFinite(v<var>alue</var>)</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -36,13 +36,13 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite <h2 id="Polyfill">Polyfill</h2> -<pre class="brush: js notranslate">if (Number.isFinite === undefined) Number.isFinite = function(value) { +<pre class="brush: js">if (Number.isFinite === undefined) Number.isFinite = function(value) { return typeof value === 'number' && isFinite(value); }</pre> <h2 id="示例">示例</h2> -<pre class="brush: js notranslate">Number.isFinite(Infinity); // false +<pre class="brush: js">Number.isFinite(Infinity); // false Number.isFinite(NaN); // false Number.isFinite(-Infinity); // false diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/number/index.html b/files/zh-cn/web/javascript/reference/global_objects/number/number/index.html index e539061589..604944ab1b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/number/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/number/number/index.html @@ -9,7 +9,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Number/Number <h2 id="语法">语法</h2> -<pre class="brush: js notranslate">new Number(<var>value</var>) +<pre class="brush: js">new Number(<var>value</var>) </pre> <h3 id="参数">参数</h3> @@ -23,7 +23,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Number/Number <h3 id="创建_Number_对象">创建 Number 对象</h3> -<pre class="brush: js notranslate">const a = new Number('123'); // a === 123 is false +<pre class="brush: js">const a = new Number('123'); // a === 123 is false const b = Number('123'); // b === 123 is true a instanceof Number; // is true b instanceof Number; // is false</pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/assign/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/assign/index.html index 1e1080be00..080c859773 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/assign/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/assign/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code>Object.assign(<var>target</var>, ...<var>sources</var>)</code></pre> +<pre class="syntaxbox"><code>Object.assign(<var>target</var>, ...<var>sources</var>)</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -53,7 +53,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign <p>这个 <a href="/zh-CN/docs/Glossary/Polyfill">polyfill</a> 不支持 symbol 属性, 由于 ES5 中本来就不存在 symbols :</p> -<pre class="notranslate">if (typeof Object.assign !== 'function') { +<pre>if (typeof Object.assign !== 'function') { // Must be writable: true, enumerable: false, configurable: true Object.defineProperty(Object, "assign", { value: function assign(target, varArgs) { // .length of function is 2 @@ -87,7 +87,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign <h3 id="Example_Cloning_an_object" name="Example:_Cloning_an_object">复制一个对象</h3> -<pre class="brush: js notranslate">const obj = { a: 1 }; +<pre class="brush: js">const obj = { a: 1 }; const copy = Object.assign({}, obj); console.log(copy); // { a: 1 } </pre> @@ -98,7 +98,7 @@ console.log(copy); // { a: 1 } <p>假如源值是一个对象的引用,它仅仅会复制其引用值。</p> -<pre class="brush: js notranslate">const log = console.log; +<pre class="brush: js">const log = console.log; function test() { 'use strict'; @@ -139,7 +139,7 @@ test(); <h3 id="Example_Merging_objects" name="Example:_Merging_objects">合并对象</h3> -<pre class="brush: js notranslate">const o1 = { a: 1 }; +<pre class="brush: js">const o1 = { a: 1 }; const o2 = { b: 2 }; const o3 = { c: 3 }; @@ -150,7 +150,7 @@ console.log(o1); // { a: 1, b: 2, c: 3 }, 注意目标对象自身也会改变 <h3 id="合并具有相同属性的对象">合并具有相同属性的对象</h3> -<pre class="brush: js notranslate">const o1 = { a: 1, b: 1, c: 1 }; +<pre class="brush: js">const o1 = { a: 1, b: 1, c: 1 }; const o2 = { b: 2, c: 2 }; const o3 = { c: 3 }; @@ -161,7 +161,7 @@ console.log(obj); // { a: 1, b: 2, c: 3 }</pre> <h3 id="Example_Symbol_properties" name="Example:_Symbol_properties">拷贝 symbol 类型的属性</h3> -<pre class="brush: js notranslate">const o1 = { a: 1 }; +<pre class="brush: js">const o1 = { a: 1 }; const o2 = { [Symbol('foo')]: 2 }; const obj = Object.assign({}, o1, o2); @@ -170,7 +170,7 @@ Object.getOwnPropertySymbols(obj); // [Symbol(foo)]</pre> <h3 id="Example_Only_own_enumerable_properties" name="Example:_Only_own_enumerable_properties">继承属性和不可枚举属性是不能拷贝的</h3> -<pre class="brush: js notranslate">const obj = Object.create({foo: 1}, { // foo 是个继承属性。 +<pre class="brush: js">const obj = Object.create({foo: 1}, { // foo 是个继承属性。 bar: { value: 2 // bar 是个不可枚举属性。 }, @@ -186,7 +186,7 @@ console.log(copy); // { baz: 3 } <h3 id="Example_Primitives" name="Example:_Primitives">原始类型会被包装为对象</h3> -<pre class="brush: js notranslate">const v1 = "abc"; +<pre class="brush: js">const v1 = "abc"; const v2 = true; const v3 = 10; const v4 = Symbol("foo") @@ -198,7 +198,7 @@ console.log(obj); // { "0": "a", "1": "b", "2": "c" }</pre> <h3 id="Example_Exceptions" name="Example:_Exceptions">异常会打断后续拷贝任务</h3> -<pre class="brush: js notranslate">const target = Object.defineProperty({}, "foo", { +<pre class="brush: js">const target = Object.defineProperty({}, "foo", { value: 1, writable: false }); // target 的 foo 属性是个只读属性。 @@ -216,7 +216,7 @@ console.log(target.baz); // undefined,第三个源对象更是不会被拷贝 <h3 id="Example_Copy_accessors" name="Example:_Copy_accessors">拷贝访问器</h3> -<pre class="brush: js notranslate">const obj = { +<pre class="brush: js">const obj = { foo: 1, get bar() { return 2; @@ -255,7 +255,7 @@ console.log(copy); <p>此{{Glossary("Polyfill","polyfill")}}不支持 symbol 属性,因为ES5 中根本没有 symbol :</p> -<pre class="brush: js notranslate">if (typeof Object.assign != 'function') { +<pre class="brush: js">if (typeof Object.assign != 'function') { // Must be writable: true, enumerable: false, configurable: true Object.defineProperty(Object, "assign", { value: function assign(target, varArgs) { // .length of function is 2 diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/create/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/create/index.html index 073605d77f..671c542a48 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/create/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/create/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/create <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="notranslate">Object.create(<var>proto,[</var><var>propertiesObject</var>])</pre> +<pre>Object.create(<var>proto,[</var><var>propertiesObject</var>])</pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -45,7 +45,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/create <p>下面的例子演示了如何使用<code>Object.create()</code>来实现类式继承。这是一个所有版本JavaScript都支持的单继承。</p> -<pre class="brush: js notranslate">// Shape - 父类(superclass) +<pre class="brush: js">// Shape - 父类(superclass) function Shape() { this.x = 0; this.y = 0; @@ -77,7 +77,7 @@ rect.move(1, 1); // Outputs, 'Shape moved.'</pre> <p>如果你希望能继承到多个对象,则可以使用混入的方式。</p> -<pre class="brush: js notranslate">function MyClass() { +<pre class="brush: js">function MyClass() { SuperClass.call(this); OtherSuperClass.call(this); } @@ -98,7 +98,7 @@ MyClass.prototype.myMethod = function() { <h3 id="使用_Object.create_的_propertyObject参数">使用 <code>Object.create</code> 的 <code>propertyObject</code>参数</h3> -<pre class="brush: js notranslate">var o; +<pre class="brush: js">var o; // 创建一个原型为null的空对象 o = Object.create(null); @@ -167,7 +167,7 @@ o2 = Object.create({}, { <p>请注意,尽管在 ES5 中 <code>Object.create</code>支持设置为<code>[[Prototype]]</code>为<code>null</code>,但因为那些ECMAScript5以前版本限制,此 polyfill 无法支持该特性。</p> -<pre class="brush: js notranslate">if (typeof Object.create !== "function") { +<pre class="brush: js">if (typeof Object.create !== "function") { Object.create = function (proto, propertiesObject) { if (typeof proto !== 'object' && typeof proto !== 'function') { throw new TypeError('Object prototype may only be an Object: ' + proto); diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/defineproperties/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/defineproperties/index.html index 483bcdf234..e4d9e9ef7a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/defineproperties/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/defineproperties/index.html @@ -14,7 +14,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="notranslate"><code>Object.defineProperties(<var>obj</var>, <var>props</var>)</code></pre> +<pre><code>Object.defineProperties(<var>obj</var>, <var>props</var>)</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -63,7 +63,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties <h2 id="例子">例子</h2> -<pre class="brush: js notranslate">var obj = {}; +<pre class="brush: js">var obj = {}; Object.defineProperties(obj, { 'property1': { value: true, @@ -80,7 +80,7 @@ Object.defineProperties(obj, { <p>假设一个原始的执行环境,所有的名称和属性都引用它们的初始值,<code>Object.defineProperties</code>几乎完全等同于(注意<code>isCallable</code>中的注释)以下JavaScript中的重新实现:</p> -<pre class="brush: js notranslate">function defineProperties(obj, properties) { +<pre class="brush: js">function defineProperties(obj, properties) { function convertToDescriptor(desc) { function hasProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/defineproperty/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/defineproperty/index.html index c711f8b4d5..b37662d5ab 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/defineproperty/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/defineproperty/index.html @@ -25,7 +25,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">Object.defineProperty(<var>obj</var>, <var>prop</var>, <var>descriptor</var>)</pre> +<pre class="syntaxbox">Object.defineProperty(<var>obj</var>, <var>prop</var>, <var>descriptor</var>)</pre> <h3 id="参数">参数</h3> @@ -135,7 +135,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty <p>记住,这些选项不一定是自身属性,也要考虑继承来的属性。为了确认保留这些默认值,在设置之前,可能要冻结 {{jsxref("Object.prototype")}},明确指定所有的选项,或者通过 {{jsxref("Object.create", "Object.create(null)")}} 将 {{jsxref("Object.prototype.__proto__", "__proto__")}} 属性指向 {{jsxref("null")}}。</p> -<pre class="brush: js notranslate">// 使用 __proto__ +<pre class="brush: js">// 使用 __proto__ var obj = {}; var descriptor = Object.create(null); // 没有继承的属性 // 默认没有 enumerable,没有 configurable,没有 writable @@ -178,7 +178,7 @@ Object.defineProperty(obj, "key", withValue("static")); <p>如果对象中不存在指定的属性,<code>Object.defineProperty()</code> 会创建这个属性。当描述符中省略某些字段时,这些字段将使用它们的默认值。</p> -<pre class="brush: js notranslate">var o = {}; // 创建一个新对象 +<pre class="brush: js">var o = {}; // 创建一个新对象 // 在对象中添加一个属性与数据描述符的示例 Object.defineProperty(o, "a", { @@ -225,7 +225,7 @@ Object.defineProperty(o, "conflict", { <p>当 <code>writable</code> 属性设置为 <code>false</code> 时,该属性被称为“不可写的”。它不能被重新赋值。</p> -<pre class="brush: js notranslate">var o = {}; // 创建一个新对象 +<pre class="brush: js">var o = {}; // 创建一个新对象 Object.defineProperty(o, 'a', { value: 37, @@ -256,7 +256,7 @@ console.log(o.a); // logs 37. The assignment didn't work. <p><code>enumerable</code> 定义了对象的属性是否可以在 {{jsxref("Statements/for...in", "for...in")}} 循环和 {{jsxref("Object.keys()")}} 中被枚举。</p> -<pre class="brush: js notranslate">var o = {}; +<pre class="brush: js">var o = {}; Object.defineProperty(o, "a", { value : 1, enumerable: true }); Object.defineProperty(o, "b", { value : 2, enumerable: false }); Object.defineProperty(o, "c", { value : 3 }); // enumerable 默认为 false @@ -296,7 +296,7 @@ p[Symbol.for('f')] // undefined</pre> <p><code>configurable</code> 特性表示对象的属性是否可以被删除,以及除 <code>value</code> 和 <code>writable</code> 特性外的其他特性是否可以被修改。</p> -<pre class="brush: js notranslate">var o = {}; +<pre class="brush: js">var o = {}; Object.defineProperty(o, 'a', { get() { return 1; }, configurable: false @@ -329,7 +329,7 @@ console.log(o.a); // logs 1</pre> <p>考虑特性被赋予的默认特性值非常重要,通常,使用点运算符和 <code>Object.defineProperty()</code> 为对象的属性赋值时,数据描述符中的属性默认值是不同的,如下例所示。</p> -<pre class="brush: js notranslate">var o = {}; +<pre class="brush: js">var o = {}; o.a = 1; // 等同于: @@ -356,7 +356,7 @@ Object.defineProperty(o, "a", { <p>下面的例子展示了如何实现一个自存档对象。当设置<code>temperature</code> 属性时,<code>archive</code> 数组会收到日志条目。</p> -<pre class="brush: js notranslate">function Archiver() { +<pre class="brush: js">function Archiver() { var temperature = null; var archive = []; @@ -382,7 +382,7 @@ arc.getArchive(); // [{ val: 11 }, { val: 13 }]</pre> <p>下面这个例子中,getter 总是会返回一个相同的值。</p> -<pre class="brush: js notranslate">var pattern = { +<pre class="brush: js">var pattern = { get: function () { return 'I alway return this string,whatever you have assigned'; }, @@ -409,7 +409,7 @@ console.log(instance.myname);</pre> <p>如果访问者的属性是被继承的,它的 <code>get</code> 和 <code>set</code> 方法会在子对象的属性被访问或者修改时被调用。如果这些方法用一个变量存值,该值会被所有对象共享。</p> -<pre class="brush: js notranslate">function myclass() { +<pre class="brush: js">function myclass() { } var value; @@ -430,7 +430,7 @@ console.log(b.x); // 1 <p>这可以通过将值存储在另一个属性中解决。在 <code>get</code> 和 <code>set</code> 方法中,<code>this</code> 指向某个被访问和修改属性的对象。</p> -<pre class="brush: js notranslate">function myclass() { +<pre class="brush: js">function myclass() { } Object.defineProperty(myclass.prototype, "x", { @@ -449,7 +449,7 @@ console.log(b.x); // undefined</pre> <p>不像访问者属性,值属性始终在对象自身上设置,而不是一个原型。然而,如果一个不可写的属性被继承,它仍然可以防止修改对象的属性。</p> -<pre class="brush: js notranslate">function myclass() { +<pre class="brush: js">function myclass() { } myclass.prototype.x = 1; diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/fromentries/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/fromentries/index.html index 80cb1de95a..d7b9c46865 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/fromentries/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/fromentries/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/fromEntries <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">Object.fromEntries(<var>iterable</var>);</pre> +<pre class="syntaxbox">Object.fromEntries(<var>iterable</var>);</pre> <h3 id="参数">参数</h3> @@ -38,7 +38,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/fromEntries <p>通过 <code>Object.fromEntries</code>, 可以将 {{jsxref("Map")}} 转换为 {{jsxref("Object")}}:</p> -<pre class="brush: js notranslate">const map = new Map([ ['foo', 'bar'], ['baz', 42] ]); +<pre class="brush: js">const map = new Map([ ['foo', 'bar'], ['baz', 42] ]); const obj = Object.fromEntries(map); console.log(obj); // { foo: "bar", baz: 42 } </pre> @@ -47,7 +47,7 @@ console.log(obj); // { foo: "bar", baz: 42 } <p>通过 <code>Object.fromEntries</code>, 可以将 {{jsxref("Array")}} 转换为 {{jsxref("Object")}}:</p> -<pre class="brush: js notranslate">const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]; +<pre class="brush: js">const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]; const obj = Object.fromEntries(arr); console.log(obj); // { 0: "a", 1: "b", 2: "c" } </pre> @@ -56,7 +56,7 @@ console.log(obj); // { 0: "a", 1: "b", 2: "c" } <p><code>Object.fromEntries</code> 是与 {{jsxref("Object.entries()")}} 相反的方法,用 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Methods_2">数组处理函数</a> 可以像下面这样转换对象:</p> -<pre class="brush: js notranslate">const object1 = { a: 1, b: 2, c: 3 }; +<pre class="brush: js">const object1 = { a: 1, b: 2, c: 3 }; const object2 = Object.fromEntries( Object.entries(object1) diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html index a5b4088128..08874a06e8 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/getownpropertydescriptor/index.html @@ -16,7 +16,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDes <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate">Object.getOwnPropertyDescriptor(<em>obj</em>, <em>prop</em>)</pre> +<pre class="syntaxbox">Object.getOwnPropertyDescriptor(<em>obj</em>, <em>prop</em>)</pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -54,7 +54,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDes <h2 id="Examples" name="Examples">示例</h2> -<pre class="brush: js notranslate">var o, d; +<pre class="brush: js">var o, d; o = { get foo() { return 17; } }; d = Object.getOwnPropertyDescriptor(o, "foo"); @@ -92,7 +92,7 @@ d = Object.getOwnPropertyDescriptor(o, "baz"); <p>在 ES5 中,如果该方法的第一个参数不是对象(而是原始类型),那么就会产生出现 {{jsxref("TypeError")}}。而在 ES2015,第一个的参数不是对象的话就会被强制转换为对象。</p> -<pre class="brush: js notranslate">Object.getOwnPropertyDescriptor('foo', 0); +<pre class="brush: js">Object.getOwnPropertyDescriptor('foo', 0); // 类型错误: "foo" 不是一个对象 // ES5 code Object.getOwnPropertyDescriptor('foo', 0); diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/hasownproperty/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/hasownproperty/index.html index 70f5f307d6..b0c254e52a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/hasownproperty/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/hasownproperty/index.html @@ -22,7 +22,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>obj</var>.hasOwnProperty(<var>prop</var>)</pre> +<pre class="syntaxbox"><var>obj</var>.hasOwnProperty(<var>prop</var>)</pre> <h3 id="参数">参数</h3> @@ -43,7 +43,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty <p>即使属性的值是 <code>null</code> 或 <code>undefined</code>,只要属性存在,<code>hasOwnProperty</code> 依旧会返回 <code>true</code>。</p> -<pre class="brush: js notranslate">o = new Object(); +<pre class="brush: js">o = new Object(); o.propOne = null; o.hasOwnProperty('propOne'); // 返回 true o.propTwo = undefined; @@ -56,7 +56,7 @@ o.hasOwnProperty('propTwo'); // 返回 true <p>下面的例子检测了对象 <code>o</code> 是否含有自身属性 <code>prop</code>:</p> -<pre class="brush: js notranslate">o = new Object(); +<pre class="brush: js">o = new Object(); o.hasOwnProperty('prop'); // 返回 false o.prop = 'exists'; o.hasOwnProperty('prop'); // 返回 true @@ -68,7 +68,7 @@ o.hasOwnProperty('prop'); // 返回 false <p>下面的例子演示了 <code>hasOwnProperty</code> 方法对待自身属性和继承属性的区别:</p> -<pre class="brush: js notranslate">o = new Object(); +<pre class="brush: js">o = new Object(); o.prop = 'exists'; o.hasOwnProperty('prop'); // 返回 true o.hasOwnProperty('toString'); // 返回 false @@ -79,7 +79,7 @@ o.hasOwnProperty('hasOwnProperty'); // 返回 false <p>下面的例子演示了如何在遍历一个对象的所有属性时忽略掉继承属性,注意这里 {{jsxref("Statements/for...in", "for...in")}} 循环只会遍历可枚举属性,所以不应该基于这个循环中没有不可枚举的属性而得出 <code>hasOwnProperty</code> 是严格限制于可枚举项目的(如同 {{jsxref("Object.getOwnPropertyNames()")}})。</p> -<pre class="brush: js notranslate">var buz = { +<pre class="brush: js">var buz = { fog: 'stack' }; @@ -98,7 +98,7 @@ for (var name in buz) { <p>JavaScript 并没有保护 <code>hasOwnProperty</code> 这个属性名,因此,当某个对象可能自有一个占用该属性名的属性时,就需要使用外部的 <code>hasOwnProperty</code> 获得正确的结果:</p> -<pre class="brush: js notranslate">var foo = { +<pre class="brush: js">var foo = { hasOwnProperty: function() { return false; }, diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/index.html index cd90b70b07..e143a7d49d 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/index.html @@ -139,24 +139,24 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object <p>下面的例子将一个空的 <code>Object</code> 对象存到 <code>o</code> 中:</p> -<pre class="brush: js notranslate">var o = new Object(); +<pre class="brush: js">var o = new Object(); </pre> -<pre class="brush: js notranslate">var o = new Object(undefined); +<pre class="brush: js">var o = new Object(undefined); </pre> -<pre class="brush: js notranslate">var o = new Object(null); +<pre class="brush: js">var o = new Object(null); </pre> <h3 id="使用_Object_生成布尔对象">使用 <code>Object</code> 生成布尔对象</h3> <p>下面的例子将{{jsxref("Boolean")}} 对象存到 <code>o</code> 中:</p> -<pre class="brush: js notranslate">// 等价于 o = new Boolean(true); +<pre class="brush: js">// 等价于 o = new Boolean(true); var o = new Object(true); </pre> -<pre class="brush: js notranslate">// 等价于 o = new Boolean(false); +<pre class="brush: js">// 等价于 o = new Boolean(false); var o = new Object(Boolean()); </pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/is/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/is/index.html index 9c3aff1abd..04a528b7b8 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/is/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/is/index.html @@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/is <p><strong>语法</strong></p> <p> - </p><pre class="syntaxbox notranslate"><code>Object.is(<var>value1</var>, <var>value2</var>);</code></pre> + </p><pre class="syntaxbox"><code>Object.is(<var>value1</var>, <var>value2</var>);</code></pre> <h3 id="参数">参数</h3> @@ -59,7 +59,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/is <h2 id="Polyfill">Polyfill</h2> -<pre class="brush: js notranslate">if (!Object.is) { +<pre class="brush: js">if (!Object.is) { Object.is = function(x, y) { // SameValue algorithm if (x === y) { // Steps 1-5, 7-10 @@ -99,7 +99,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/is <h3 id="使用_Object.is">使用 Object.is</h3> -<pre class="brush: js notranslate">Object.is('foo', 'foo'); // true +<pre class="brush: js">Object.is('foo', 'foo'); // true Object.is(window, window); // true Object.is('foo', 'bar'); // false diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/issealed/index.html b/files/zh-cn/web/javascript/reference/global_objects/object/issealed/index.html index d4bb3a438e..e6a895f345 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/issealed/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/object/issealed/index.html @@ -14,7 +14,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/isSealed <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code>Object.isSealed(<em>obj</em>)</code></pre> +<pre class="syntaxbox"><code>Object.isSealed(<em>obj</em>)</code></pre> <h3 id="参数">参数</h3> @@ -33,7 +33,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/isSealed <h2 id="Examples" name="Examples">例子</h2> -<pre class="brush: js notranslate">// 新建的对象默认不是密封的. +<pre class="brush: js">// 新建的对象默认不是密封的. var empty = {}; Object.isSealed(empty); // === false @@ -72,7 +72,7 @@ Object.isFrozen(s3); // === true ,访问器属性不考虑可写不可写,只 <p>在ES5中,如果这个方法的参数不是一个对象(一个原始类型),那么它会导致{{jsxref("TypeError")}}。在ES2015中,非对象参数将被视为是一个密封的普通对象,只返回<code>true</code>。</p> -<pre class="brush: js notranslate">Object.isSealed(1); +<pre class="brush: js">Object.isSealed(1); // TypeError: 1 is not an object (ES5 code) Object.isSealed(1); diff --git a/files/zh-cn/web/javascript/reference/global_objects/parseint/index.html b/files/zh-cn/web/javascript/reference/global_objects/parseint/index.html index 2bbf25fe98..cf2555558b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/parseint/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/parseint/index.html @@ -22,7 +22,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/parseInt <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">parseInt(<em>string</em>, <em>radix</em>);</pre> +<pre class="syntaxbox">parseInt(<em>string</em>, <em>radix</em>);</pre> <h3 id="参数">参数</h3> @@ -48,7 +48,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/parseInt <li>第一个非空格字符不能转换为数字。</li> </ul> -<pre class="notranslate">parseInt('123', 5) // 将'123'看作5进制数,返回十进制数38 => 1*5^2 + 2*5^1 + 3*5^0 = 38</pre> +<pre>parseInt('123', 5) // 将'123'看作5进制数,返回十进制数38 => 1*5^2 + 2*5^1 + 3*5^0 = 38</pre> <h2 id="描述_2"><a id="描述" name="描述">描述</a></h2> @@ -89,7 +89,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/parseInt <p>以下例子均返回<code>15</code>:</p> -<pre class="brush: js notranslate">parseInt("0xF", 16); +<pre class="brush: js">parseInt("0xF", 16); parseInt("F", 16); parseInt("17", 8); parseInt(021, 8); @@ -105,13 +105,13 @@ parseInt("12", 13);</pre> <p>以下例子均返回 <code>NaN</code>:</p> -<pre class="brush: js notranslate">parseInt("Hello", 8); // 根本就不是数值 +<pre class="brush: js">parseInt("Hello", 8); // 根本就不是数值 parseInt("546", 2); // 除了“0、1”外,其它数字都不是有效二进制数字 </pre> <p>以下例子均返回 <code>-15</code>:</p> -<pre class="brush: js notranslate">parseInt("-F", 16); +<pre class="brush: js">parseInt("-F", 16); parseInt("-0F", 16); parseInt("-0XF", 16); parseInt(-15.1, 10); @@ -124,19 +124,19 @@ parseInt("-12", 13); <p>下例中全部返回 <code>4</code>:</p> -<pre class="brush: js notranslate">parseInt(4.7, 10); +<pre class="brush: js">parseInt(4.7, 10); parseInt(4.7 * 1e22, 10); // 非常大的数值变成 4 parseInt(0.00000000000434, 10); // 非常小的数值变成 4</pre> <p>下面的例子返回 <code>224</code></p> -<pre class="brush: js notranslate">parseInt("0e0",16);</pre> +<pre class="brush: js">parseInt("0e0",16);</pre> <h2 id="没有指定_radix_参数时的八进制解析" style="margin-bottom: 20px; line-height: 30px;">没有指定 <code>radix</code> 参数时的八进制解析</h2> <p>尽管 ECMAScript 3 已经不赞成这种做法,且 ECMAScript 5 已经禁止了这种做法,但是仍然有很多实现环境仍然把以 0 开头的数值字符串(numeric string)解释为一个八进制数。下面的例子可能返回八进制的结果,也可能返回十进制的结果。<strong>总是指定一个基数(radix)可以避免这种不可靠的行为。</strong></p> -<pre class="brush: js notranslate">parseInt("0e0"); +<pre class="brush: js">parseInt("0e0"); // 0 parseInt("08"); @@ -157,7 +157,7 @@ parseInt("08"); <p>有时采用一个更严格的方法来解析整型值很有用。此时可以使用正则表达式:</p> -<pre class="brush: js notranslate">filterInt = function (value) { +<pre class="brush: js">filterInt = function (value) { if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value)) return Number(value); return NaN; diff --git a/files/zh-cn/web/javascript/reference/global_objects/promise/all/index.html b/files/zh-cn/web/javascript/reference/global_objects/promise/all/index.html index c2d22ae1cd..113760c25d 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/promise/all/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/promise/all/index.html @@ -21,7 +21,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>Promise.all(iterable)</var>;</pre> +<pre class="syntaxbox"><var>Promise.all(iterable)</var>;</pre> <h3 id="参数">参数</h3> @@ -56,7 +56,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all <p><code>Promise.all</code> 等待所有都完成(或第一个失败)。</p> -<pre class="brush: js notranslate">var p1 = Promise.resolve(3); +<pre class="brush: js">var p1 = Promise.resolve(3); var p2 = 1337; var p3 = new Promise((resolve, reject) => { setTimeout(resolve, 100, 'foo'); @@ -68,7 +68,7 @@ Promise.all([p1, p2, p3]).then(values => { <p>如果参数中包含非 <code>promise</code> 值,这些值将被忽略,但仍然会被放在返回数组中(如果 <code>promise</code> 完成的话):</p> -<pre class="brush: js notranslate">// this will be counted as if the iterable passed is empty, so it gets fulfilled +<pre class="brush: js">// this will be counted as if the iterable passed is empty, so it gets fulfilled var p = Promise.all([1,2,3]); // this will be counted as if the iterable passed contains only the resolved promise with value "444", so it gets fulfilled var p2 = Promise.all([1,2,3, Promise.resolve(444)]); @@ -91,7 +91,7 @@ setTimeout(function(){ <p>下面的例子中演示了 <code>Promise.all</code> 的异步性(如果传入的可迭代对象是空的,就是同步):</p> -<pre class="brush: js notranslate">// we are passing as argument an array of promises that are already resolved, +<pre class="brush: js">// we are passing as argument an array of promises that are already resolved, // to trigger Promise.all as soon as possible var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; @@ -113,7 +113,7 @@ setTimeout(function(){ <p>如果 <code>Promise.all</code> 失败,也是一样的:</p> -<pre class="brush: js notranslate">var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)]; +<pre class="brush: js">var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)]; var p = Promise.all(mixedPromisesArray); console.log(p); setTimeout(function(){ @@ -129,7 +129,7 @@ setTimeout(function(){ <p>但是,<code>Promise.all</code> <strong>当且仅当</strong>传入的可迭代对象为空时为同步:</p> -<pre class="brush: js notranslate">var p = Promise.all([]); // will be immediately resolved +<pre class="brush: js">var p = Promise.all([]); // will be immediately resolved var p2 = Promise.all([1337, "hi"]); // non-promise values will be ignored, but the evaluation will be done asynchronously console.log(p); console.log(p2) @@ -149,7 +149,7 @@ setTimeout(function(){ <p><code>Promise.all</code> 在任意一个传入的 <code>promise</code> 失败时返回失败。例如,如果你传入的 <code>promise</code>中,有四个 <code>promise</code> 在一定的时间之后调用成功函数,有一个立即调用失败函数,那么 <code>Promise.all</code> 将立即变为失败。</p> -<pre class="brush: js notranslate">var p1 = new Promise((resolve, reject) => { +<pre class="brush: js">var p1 = new Promise((resolve, reject) => { setTimeout(resolve, 1000, 'one'); }); var p2 = new Promise((resolve, reject) => { diff --git a/files/zh-cn/web/javascript/reference/global_objects/promise/allsettled/index.html b/files/zh-cn/web/javascript/reference/global_objects/promise/allsettled/index.html index a448dfb79b..d6ceaaa2ad 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/promise/allsettled/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/promise/allsettled/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise/allSettled <h2 id="句法">句法</h2> -<pre class="notranslate"><em>Promise</em>.allSettled(<em>iterable</em>);</pre> +<pre><em>Promise</em>.allSettled(<em>iterable</em>);</pre> <h3 id="参数">参数</h3> diff --git a/files/zh-cn/web/javascript/reference/global_objects/promise/any/index.html b/files/zh-cn/web/javascript/reference/global_objects/promise/any/index.html index 25e87a91af..b61b833f5f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/promise/any/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/promise/any/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise/any <h2 id="语法">语法</h2> -<pre class="notranslate">Promise.any(<var>iterable</var>);</pre> +<pre>Promise.any(<var>iterable</var>);</pre> <h3 id="参数">参数</h3> @@ -63,7 +63,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise/any <p>即使第一个返回的 promise 是失败的,<code>Promise.any()</code> 依然使用第一个成功状态的 promise 来返回。这与使用首个(无论 rejected 还是 fullfiled)promise 来返回的 {{jsxref("Promise.race()")}} 相反。</p> -<pre class="brush: js notranslate">const pErr = new Promise((resolve, reject) => { +<pre class="brush: js">const pErr = new Promise((resolve, reject) => { reject("总是失败"); }); @@ -86,7 +86,7 @@ Promise.any([pErr, pSlow, pFast]).then((value) => { <p>如果没有 fulfilled (成功的) promise,<code>Promise.any()</code> 返回 {{jsxref("AggregateError")}} 错误。</p> -<pre class="brush: js notranslate">const pErr = new Promise((resolve, reject) => { +<pre class="brush: js">const pErr = new Promise((resolve, reject) => { reject('总是失败'); }); @@ -100,7 +100,7 @@ Promise.any([pErr]).catch((err) => { <p>在这个例子,我们有一个获取图片并返回 blob 的函数,我们使用 <code>Promise.any()</code> 来获取一些图片并显示第一张有效的图片(即最先 resolved 的那个 promise)。</p> -<pre class="brush: js notranslate">function fetchAndDecode(url) { +<pre class="brush: js">function fetchAndDecode(url) { return fetch(url).then(response => { if(!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); diff --git a/files/zh-cn/web/javascript/reference/global_objects/promise/index.html b/files/zh-cn/web/javascript/reference/global_objects/promise/index.html index 3dd832b401..31420f60c5 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/promise/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/promise/index.html @@ -46,7 +46,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise <p>我们可以用 <code>promise.then()</code>,<code>promise.catch()</code> 和 <code>promise.finally()</code> 这些方法将进一步的操作与一个变为已敲定状态的 promise 关联起来。这些方法还会返回一个新生成的 promise 对象,这个对象可以被非强制性的用来做链式调用,就像这样:</p> -<pre class="notranslate">const myPromise = +<pre>const myPromise = (new Promise(myExecutorFunc)) .then(handleFulfilledA,handleRejectedA) .then(handleFulfilledB,handleRejectedB) @@ -65,7 +65,7 @@ const myPromise = <p>这两个函数的签名很简单,它们只接受一个任意类型的参数。这些函数由您(编程者)编写。这些函数的终止状态决定着链式调用中下一个promise的"已敲定 (settled)"状态是什么。任何不是 <code>throw</code> 的终止都会创建一个"已决议(resolved)"状态,而以 <code>throw</code> 终止则会创建一个"已拒绝"状态。</p> -<pre class="notranslate">handleFulfilled(value) { /*...*/; return nextValue; } +<pre>handleFulfilled(value) { /*...*/; return nextValue; } handleRejection(reason) { /*...*/; throw nextReason; } handleRejection(reason) { /*...*/; return nextValue; }</pre> @@ -75,21 +75,21 @@ handleRejection(reason) { /*...*/; return nextValue; }</pre> <p>链式调用中的 promise 们就像俄罗斯套娃一样,是嵌套起来的,但又像是一个栈,每个都必须从顶端被弹出。链式调用中的第一个 promise 是嵌套最深的一个,也将是第一个被弹出的。</p> -<pre class="notranslate">(promise D, (promise C, (promise B, (promise A) ) ) )</pre> +<pre>(promise D, (promise C, (promise B, (promise A) ) ) )</pre> <p>当存在一个 <code>nextValue</code> 是 promise 时,就会出现一种动态的替换效果。<code>return</code> 会导致一个 promise 被弹出,但这个 <code>nextValue</code> promise 则会被推入被弹出 promise 原来的位置。对于上面所示的嵌套场景,假设与 "promise B" 相关的 <code>.then()</code> 返回了一个值为 "promise X" 的 <code>nextValue</code> 。那么嵌套的结果看起来就会是这样:</p> -<pre class="notranslate">(promise D, (promise C, (promise X) ) )</pre> +<pre>(promise D, (promise C, (promise X) ) )</pre> <p>一个 promise 可能会参与不止一次的嵌套。对于下面的代码,<code>promiseA</code> 向"已敲定"("settled")状态的过渡会导致两个实例的 <code>.then</code> 都被调用。</p> -<pre class="notranslate">const promiseA = new Promise(myExecutorFunc); +<pre>const promiseA = new Promise(myExecutorFunc); const promiseB = promiseA.then(handleFulfilled1, handleRejected1); const promiseC = promiseA.then(handleFulfilled2, handleRejected2); </pre> <p>一个已经处于"已敲定"("settled")状态的 promise 也可以接收操作。在那种情况下,(如果没有问题的话,)这个操作会被作为第一个异步操作被执行。注意,所有的 promise 都一定是异步的。因此,一个已经处于"已敲定"("settled")状态的 promise 中的操作只有 promise 链式调用的栈被清空了和一个事件循环过去了之后才会被执行。这种效果跟 <code>setTimeout(action, 10)</code> 特别相似。</p> -<pre class="notranslate">const promiseA = new Promise( (resolutionFunc,rejectionFunc) => { +<pre>const promiseA = new Promise( (resolutionFunc,rejectionFunc) => { resolutionFunc(777); }); // 这时,"promiseA" 已经被敲定了。 @@ -155,7 +155,7 @@ console.log("immediate logging"); <p><code>Promise</code> 对象是由关键字 <code>new</code> 及其构造函数来创建的。该构造函数会把一个叫做“处理器函数”(executor function)的函数作为它的参数。这个“处理器函数”接受两个函数——<code>resolve</code> 和 <code>reject</code> ——作为其参数。当异步任务顺利完成且返回结果值时,会调用 <code>resolve</code> 函数;而当异步任务失败且返回失败原因(通常是一个错误对象)时,会调用<code>reject</code> 函数。</p> -<pre class="brush: js notranslate">const myFirstPromise = new Promise((resolve, reject) => { +<pre class="brush: js">const myFirstPromise = new Promise((resolve, reject) => { // ?做一些异步操作,最终会调用下面两者之一: // // resolve(someValue); // fulfilled @@ -165,7 +165,7 @@ console.log("immediate logging"); <p>想要某个函数拥有promise功能,只需让其返回一个promise即可。</p> -<pre class="brush: js notranslate">function myAsyncFunction(url) { +<pre class="brush: js">function myAsyncFunction(url) { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open("GET", url); @@ -179,7 +179,7 @@ console.log("immediate logging"); <h3 id="基础示例">基础示例</h3> -<pre class="brush: js notranslate">let myFirstPromise = new Promise(function(resolve, reject){ +<pre class="brush: js">let myFirstPromise = new Promise(function(resolve, reject){ //当异步代码执行成功时,我们才会调用resolve(...), 当异步代码失败时就会调用reject(...) //在本例中,我们使用setTimeout(...)来模拟异步代码,实际编码时可能是XHR请求或是HTML5的一些API方法. setTimeout(function(){ @@ -196,7 +196,7 @@ myFirstPromise.then(function(successMessage){ <h3 id="高级示例">高级示例</h3> -<pre class="brush: html hidden notranslate"><button id="btn">Make a promise!</button> +<pre class="brush: html hidden"><button id="btn">Make a promise!</button> <div id="log"></div> </pre> @@ -204,7 +204,7 @@ myFirstPromise.then(function(successMessage){ <p>Promise 的值的填充过程都被日志记录(logged)下来,这些日志信息展示了方法中的同步代码和异步代码是如何通过Promise完成解耦的。</p> -<pre class="brush: js notranslate">'use strict'; +<pre class="brush: js">'use strict'; var promiseCount = 0; function testPromise() { @@ -247,7 +247,7 @@ function testPromise() { ') Promise made (<small>同步代码结束</small>)<br/>'); }</pre> -<pre class="brush:js hidden notranslate">if ("Promise" in window) { +<pre class="brush:js hidden">if ("Promise" in window) { let btn = document.getElementById("btn"); btn.addEventListener("click",testPromise); } else { diff --git a/files/zh-cn/web/javascript/reference/global_objects/promise/race/index.html b/files/zh-cn/web/javascript/reference/global_objects/promise/race/index.html index fab2fd64a9..569f7d9d50 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/promise/race/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/promise/race/index.html @@ -15,7 +15,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise/race <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><var>Promise.race(iterable)</var>;</pre> +<pre class="syntaxbox"><var>Promise.race(iterable)</var>;</pre> <h3 id="参数"><strong>参数</strong></h3> @@ -40,7 +40,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise/race <h3 id="Promise.race的异步性">Promise.race的异步性</h3> -<pre class="brush: js notranslate">// we are passing as argument an array of promises that are already resolved, +<pre class="brush: js">// we are passing as argument an array of promises that are already resolved, // to trigger Promise.race as soon as possible var resolvedPromisesArray = [Promise.resolve(33), Promise.resolve(44)]; @@ -61,7 +61,7 @@ setTimeout(function(){ <h3 id="使用_Promise.race_–_setTimeout_的示例">使用 Promise.race – setTimeout 的示例</h3> -<pre class="brush: js notranslate">var p1 = new Promise(function(resolve, reject) { +<pre class="brush: js">var p1 = new Promise(function(resolve, reject) { setTimeout(resolve, 500, "one"); }); var p2 = new Promise(function(resolve, reject) { diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/index.html index b15511bc6a..f29774284a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/index.html @@ -24,7 +24,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Proxy <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">const <var>p</var> = new Proxy(<var>target</var>, <var>handler</var>)</pre> +<pre class="syntaxbox">const <var>p</var> = new Proxy(<var>target</var>, <var>handler</var>)</pre> <h3 id="参数">参数</h3> @@ -85,7 +85,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Proxy <p>在以下简单的例子中,当对象中不存在属性名时,默认返回值为 <code>37</code>。下面的代码以此展示了 {{jsxref("Global_Objects/Proxy/handler/get", "get")}} handler 的使用场景。</p> -<pre class="brush: js notranslate">const handler = { +<pre class="brush: js">const handler = { get: function(obj, prop) { return prop in obj ? obj[prop] : 37; } @@ -103,7 +103,7 @@ console.log('c' in p, p.c); // false, 37 <p>在以下例子中,我们使用了一个原生 JavaScript 对象,代理会将所有应用到它的操作转发到这个对象上。</p> -<pre class="brush: js notranslate">let target = {}; +<pre class="brush: js">let target = {}; let p = new Proxy(target, {}); p.a = 37; // 操作转发到目标 @@ -115,7 +115,7 @@ console.log(target.a); // 37. 操作已经被正确地转发 <p>通过代理,你可以轻松地验证向一个对象的传值。下面的代码借此展示了 {{jsxref("Global_Objects/Proxy/handler/set", "set")}} handler 的作用。</p> -<pre class="brush: js notranslate">let validator = { +<pre class="brush: js">let validator = { set: function(obj, prop, value) { if (prop === 'age') { if (!Number.isInteger(value)) { @@ -152,7 +152,7 @@ person.age = 300; <p>方法代理可以轻松地通过一个新构造函数来扩展一个已有的构造函数。这个例子使用了<a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/construct"><code>construct</code></a>和<code><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Proxy/handler/apply">apply</a></code>。</p> -<pre class="brush: js notranslate">function extend(sup, base) { +<pre class="brush: js">function extend(sup, base) { var descriptor = Object.getOwnPropertyDescriptor( base.prototype, "constructor" ); @@ -193,7 +193,7 @@ console.log(Peter.age); // 13</pre> <p>有时,我们可能需要互换两个不同的元素的属性或类名。下面的代码以此为目标,展示了 {{jsxref("Global_Objects/Proxy/handler/set", "set")}} handler 的使用场景。</p> -<pre class="brush: js notranslate">let view = new Proxy({ +<pre class="brush: js">let view = new Proxy({ selected: null }, { set: function(obj, prop, newval) { @@ -228,7 +228,7 @@ console.log(i2.getAttribute('aria-selected')); // 'true' <p>以下<code>products</code>代理会计算传值并根据需要转换为数组。这个代理对象同时支持一个叫做 <code>latestBrowser</code>的附加属性,这个属性可以同时作为 getter 和 setter。</p> -<pre class="brush: js notranslate">let products = new Proxy({ +<pre class="brush: js">let products = new Proxy({ browsers: ['Internet Explorer', 'Netscape'] }, { get: function(obj, prop) { @@ -273,7 +273,7 @@ console.log(products.latestBrowser); // 'Chrome' <p>以下代理为数组扩展了一些实用工具。如你所见,通过 Proxy,我们可以灵活地“定义”属性,而不需要使用 {{jsxref("Object.defineProperties")}} 方法。以下例子可以用于通过单元格来查找表格中的一行。在这种情况下,target 是 <code><a href="/zh-CN/docs/DOM/table.rows">table.rows</a></code>。</p> -<pre class="brush: js notranslate">let products = new Proxy([ +<pre class="brush: js">let products = new Proxy([ { name: 'Firefox' , type: 'browser' }, { name: 'SeaMonkey' , type: 'browser' }, { name: 'Thunderbird', type: 'mailer' } @@ -333,7 +333,7 @@ console.log(products.number); // 3 <p>出于教学目的,这里为了创建一个完整的 traps 列表示例,我们将尝试代理化一个非原生对象,这特别适用于这类操作:由 <a href="/zh-CN/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support">发布在 document.cookie页面上的“小型框架”</a>创建的<code>docCookies</code>全局对象。</p> -<pre class="brush: js notranslate">/* +<pre class="brush: js">/* var docCookies = ... get the "docCookies" object here: https://developer.mozilla.org/zh-CN/docs/DOM/document.cookie#A_little_framework.3A_a_complete_cookies_reader.2Fwriter_with_full_unicode_support */ diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/index.html index 71a257174f..897a2e9954 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/index.html @@ -9,7 +9,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">new Proxy(<var>target</var>, <var>handler</var>)</pre> +<pre class="syntaxbox">new Proxy(<var>target</var>, <var>handler</var>)</pre> <h3 id="参数">参数</h3> @@ -70,7 +70,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Proxy/Proxy <p>本例中,被代理对象有两个属性: <code>notProxied</code> 和 <code>proxied</code> 。我们定义了一个处理函数,它为 <code>proxied</code> 属性返回一个不同的值,而其他属性返回原值。</p> -<pre class="brush: js notranslate">const target = { +<pre class="brush: js">const target = { notProxied: "original value", proxied: "original value" }; diff --git a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.html b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.html index 51f7093d50..686169d215 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/proxy/proxy/preventextensions/index.html @@ -14,7 +14,7 @@ original_slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/preventExte <h2 id="语法">语法</h2> -<pre class="brush: js notranslate">var p = new Proxy(target, { +<pre class="brush: js">var p = new Proxy(target, { preventExtensions: function(target) { } }); @@ -58,7 +58,7 @@ original_slug: Web/JavaScript/Reference/Global_Objects/Proxy/handler/preventExte <p>以下代码演示了如何拦截{{jsxref("Object.preventExtensions()")}}。</p> -<pre class="brush: js notranslate">var p = new Proxy({}, { +<pre class="brush: js">var p = new Proxy({}, { preventExtensions: function(target) { console.log('called'); Object.preventExtensions(target); @@ -72,7 +72,7 @@ console.log(Object.preventExtensions(p)); // "called" <p>以下代码违反了约束.</p> -<pre class="brush: js notranslate">var p = new Proxy({}, { +<pre class="brush: js">var p = new Proxy({}, { preventExtensions: function(target) { return true; } diff --git a/files/zh-cn/web/javascript/reference/global_objects/reflect/construct/index.html b/files/zh-cn/web/javascript/reference/global_objects/reflect/construct/index.html index b54e69bb3c..311c16ca50 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/reflect/construct/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/reflect/construct/index.html @@ -9,7 +9,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/construct <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">Reflect.construct(target, argumentsList[, newTarget]) +<pre class="syntaxbox">Reflect.construct(target, argumentsList[, newTarget]) </pre> <h3 id="参数">参数</h3> @@ -35,14 +35,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/construct <p><code>Reflect.construct</code>允许你使用可变的参数来调用构造函数 ,这和使用<a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/new">new操作符</a>搭配<a href="https://developer.mozilla.org/ zh-CN/docs/Web/JavaScript/Reference/Operators/new">对象展开符</a>调用一样。</p> -<pre class="brush: js notranslate">var obj = new Foo(...args); +<pre class="brush: js">var obj = new Foo(...args); var obj = Reflect.construct(Foo, args); </pre> <h3 id="Reflect.construct_vs_Object.create"><code>Reflect.construct()</code> vs <code>Object.create()</code></h3> <p><code>在新语法Reflect</code>出现之前,是通过明确指定构造函数和原型对象( 使用{{jsxref("Object.create()")}})来创建一个对象的。</p> -<pre class="brush: js notranslate">function OneClass() { +<pre class="brush: js">function OneClass() { this.name = 'one'; } @@ -72,7 +72,7 @@ console.log(obj2 instanceof OtherClass); // true</pre> <p>当调用<code>Reflect.construct()</code>来创建对象,<code>new.target</code>值会自动指定到<code>target</code>(或者newTarget,前提是newTarget指定了)。</p> -<pre class="brush: js notranslate">function OneClass() { +<pre class="brush: js">function OneClass() { console.log('OneClass'); console.log(new.target); } @@ -101,7 +101,7 @@ OneClass.apply(obj3, args); <h3 id="使用_Reflect.construct">使用 <code>Reflect.construct()</code></h3> -<pre class="brush: js notranslate">var d = Reflect.construct(Date, [1776, 6, 4]); +<pre class="brush: js">var d = Reflect.construct(Date, [1776, 6, 4]); d instanceof Date; // true d.getFullYear(); // 1776 </pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/reflect/defineproperty/index.html b/files/zh-cn/web/javascript/reference/global_objects/reflect/defineproperty/index.html index 14882c24b9..9fc242fd8f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/reflect/defineproperty/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/reflect/defineproperty/index.html @@ -14,7 +14,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">Reflect.defineProperty(target, propertyKey, attributes) +<pre class="syntaxbox">Reflect.defineProperty(target, propertyKey, attributes) </pre> <h3 id="参数">参数</h3> @@ -48,7 +48,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Reflect/defineProperty <h3 id="使用_Reflect.defineProperty">使用 <code>Reflect.defineProperty()</code></h3> -<pre class="notranslate">let obj = {} +<pre>let obj = {} Reflect.defineProperty(obj, 'x', {value: 7}) // true obj.x // 7</pre> @@ -56,7 +56,7 @@ obj.x // 7</pre> <p>{{jsxref("Object.defineProperty")}} 方法,如果成功则返回一个对象,否则抛出一个 {{jsxref("TypeError")}} 。另外,当定义一个属性时,你也可以使用 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/try...catch">try...catch</a></code> 去捕获其中任何的错误。而因为 <code>Reflect.defineProperty</code> 返回 Boolean 值作为成功的标识,所以只能使用 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if...else</a></code> :</p> -<pre class="brush: js notranslate">if (Reflect.defineProperty(target, property, attributes)) { +<pre class="brush: js">if (Reflect.defineProperty(target, property, attributes)) { // 成功 } else { // 失败 diff --git a/files/zh-cn/web/javascript/reference/global_objects/reflect/index.html b/files/zh-cn/web/javascript/reference/global_objects/reflect/index.html index 4b430c4772..2b19f1fc92 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/reflect/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/reflect/index.html @@ -55,7 +55,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Reflect <h3 id="检测一个对象是否存在特定属性">检测一个对象是否存在特定属性</h3> -<pre class="notranslate">const duck = { +<pre>const duck = { name: 'Maurice', color: 'white', greeting: function() { @@ -70,12 +70,12 @@ Reflect.has(duck, 'haircut'); <h3 id="返回这个对象自身的属性">返回这个对象自身的属性</h3> -<pre class="notranslate">Reflect.ownKeys(duck); +<pre>Reflect.ownKeys(duck); // [ "name", "color", "greeting" ]</pre> <h3 id="为这个对象添加一个新的属性">为这个对象添加一个新的属性</h3> -<pre class="notranslate">Reflect.set(duck, 'eyes', 'black'); +<pre>Reflect.set(duck, 'eyes', 'black'); // returns "true" if successful // "duck" now contains the property "eyes: 'black'"</pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/regexp/index.html b/files/zh-cn/web/javascript/reference/global_objects/regexp/index.html index 2a1e6ffcf5..a4ca838294 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/regexp/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/regexp/index.html @@ -30,7 +30,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/RegExp <p>以下三种表达式都会创建相同的正则表达式:</p> -<pre class="brush: js notranslate" style="font-size: 14px;">/ab+c/i; //字面量形式 +<pre class="brush: js" style="font-size: 14px;">/ab+c/i; //字面量形式 new RegExp('ab+c', 'i'); // 首个参数为字符串模式的构造函数 new RegExp(/ab+c/, 'i'); // 首个参数为常规字面量的构造函数</pre> @@ -46,7 +46,7 @@ new RegExp(/ab+c/, 'i'); // 首个参数为常规字面量的构造函数</pre> <p>比如,以下是等价的:</p> -<pre class="brush: js notranslate">var re = new RegExp("\\w+"); +<pre class="brush: js">var re = new RegExp("\\w+"); var re = /\w+/;</pre> <h3 id="Perl-like_RegExp_属性">Perl-like RegExp 属性</h3> @@ -123,7 +123,7 @@ var re = /\w+/;</pre> <p>在替换的文本中,脚本中使用 <code>$1</code> 和 <code>$2</code> 指明括号里先前的匹配.</p> -<pre class="brush: js notranslate">let re = /(\w+)\s(\w+)/; +<pre class="brush: js">let re = /(\w+)\s(\w+)/; let str = "John Smith"; let newstr = str.replace(re, "$2, $1"); console.log(newstr); @@ -135,7 +135,7 @@ console.log(newstr); <p>对于不同的平台(Unix,Windows等等),其默认的行结束符是不一样的. 而下面的划分方式适用于所有平台。</p> -<pre class="notranslate">let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end' +<pre>let text = 'Some text\nAnd some more\r\nAnd yet\rThis is the end' let lines = text.split(/\r\n|\r|\n/) console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is the end' ] </pre> @@ -144,7 +144,7 @@ console.log(lines) // logs [ 'Some text', 'And some more', 'And yet', 'This is t <h3 id="在多行文本中使用正则表达式">在多行文本中使用正则表达式</h3> -<pre class="brush: js notranslate">let s = "Please yes\nmake my day!"; +<pre class="brush: js">let s = "Please yes\nmake my day!"; s.match(/yes.*day/); // Returns null @@ -156,7 +156,7 @@ s.match(/yes[^]*day/); <p>带有{{JSxRef("Global_Objects/RegExp/sticky", "sticky")}}标志的正则表达式将会从源字符串的{{jsxref("RegExp.prototype.lastIndex")}}位置开始匹配,也就是进行“粘性匹配”。</p> -<pre class="brush: js notranslate">let str = '#foo#' +<pre class="brush: js">let str = '#foo#' let regex = /foo/y regex.lastIndex = 1 @@ -169,7 +169,7 @@ regex.lastIndex // 0 (reset after match failure)</pre> <p>如果正则表达式有粘性 <code>y</code> 标志,下一次匹配一定在 <code>lastIndex</code> 位置开始;如果正则表达式有全局 <code>g</code> 标志,下一次匹配可能在 <code>lastIndex</code> 位置开始,也可能在这个位置的后面开始。</p> -<pre class="brush: js notranslate">re = /\d/y; +<pre class="brush: js">re = /\d/y; while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex); // [ '1', index: 0, input: '123 456', groups: undefined ] AND re.lastIndex 1 @@ -187,7 +187,7 @@ while (r = re.exec("123 456")) console.log(r, "AND re.lastIndex", re.lastIndex); <p>下例展示了怎样从一个单词中分离出 Unicode 字符。</p> -<pre class="brush: js notranslate">let text = "Образец text на русском языке"; +<pre class="brush: js">let text = "Образец text на русском языке"; let regex = /[\u0400-\u04FF]+/g; let match = regex.exec(text); @@ -204,7 +204,7 @@ console.log(regex.lastIndex); // prints "15" <h3 id="从_URL_中提取子域名">从 URL 中提取子域名</h3> -<pre class="brush: js notranslate">var url = "http://xxx.domain.com"; +<pre class="brush: js">var url = "http://xxx.domain.com"; console.log(/[^.]+/.exec(url)[0].substr(7)); // logs "xxx" </pre> @@ -248,7 +248,7 @@ console.log(/[^.]+/.exec(url)[0].substr(7)); // logs "xxx" <p>Starting with Gecko 34 {{geckoRelease(34)}}, in the case of a capturing group with quantifiers preventing its exercise, the matched text for a capturing group is now <code>undefined</code> instead of an empty string:</p> -<pre class="notranslate"><code>// Firefox 33 or older +<pre><code>// Firefox 33 or older 'x'.replace(/x(.)?/g, function(m, group) { console.log("'group:" + group + "'"); }); // 'group:' diff --git a/files/zh-cn/web/javascript/reference/global_objects/regexp/regexp/index.html b/files/zh-cn/web/javascript/reference/global_objects/regexp/regexp/index.html index 1457ab4f59..008b4d7d76 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/regexp/regexp/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/regexp/regexp/index.html @@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/RegExp <p>可以使用字面量、构造函数和工厂方法来创建正则表达式</p> -<pre class="syntaxbox notranslate">/<var>pattern</var>/<var>flags</var> +<pre class="syntaxbox">/<var>pattern</var>/<var>flags</var> new RegExp(<var>pattern</var>[, <var>flags</var>]) RegExp(<var>pattern</var>[, <var>flags</var>]) </pre> @@ -68,7 +68,7 @@ RegExp(<var>pattern</var>[, <var>flags</var>]) <p>以下三个表达式创建相同的正则表达式:</p> -<pre class="brush: js notranslate">/ab+c/i +<pre class="brush: js">/ab+c/i new RegExp(/ab+c/, 'i') // 字面量 new RegExp('ab+c', 'i') // 构造函数 </pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/regexp/test/index.html b/files/zh-cn/web/javascript/reference/global_objects/regexp/test/index.html index 24ddd6daa0..d1f4ed7183 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/regexp/test/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/regexp/test/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/test <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="notranslate"><var>regexObj</var>.test(str)</pre> +<pre><var>regexObj</var>.test(str)</pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -42,7 +42,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/RegExp/test <p>一个简单的例子,测试 "hello" 是否包含在字符串的最开始,返回布尔值。</p> -<pre class="brush: js notranslate">let str = 'hello world!'; +<pre class="brush: js">let str = 'hello world!'; let result = /^hello/.test(str); console.log(result); // true @@ -50,7 +50,7 @@ console.log(result); <p>下例打印一条信息,该信息内容取决于是否成功通过指定测试:</p> -<pre class="brush: js notranslate">function testinput(re, str){ +<pre class="brush: js">function testinput(re, str){ var midstring; if (re.test(str)) { midstring = " contains "; @@ -67,7 +67,7 @@ console.log(result); <p>下面的实例表现了这种行为: </p> -<pre class="brush: js notranslate">var regex = /foo/g; +<pre class="brush: js">var regex = /foo/g; // regex.lastIndex is at 0 regex.test('foo'); // true diff --git a/files/zh-cn/web/javascript/reference/global_objects/set/@@iterator/index.html b/files/zh-cn/web/javascript/reference/global_objects/set/@@iterator/index.html index fa3f7c61e5..8ab98bf9ee 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/set/@@iterator/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/set/@@iterator/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/@@iterator <h2 id="Syntax">Syntax</h2> -<pre class="syntaxbox notranslate"><code><em>mySet</em>[Symbol.iterator]</code></pre> +<pre class="syntaxbox"><code><em>mySet</em>[Symbol.iterator]</code></pre> <h3 id="Return_value">Return value</h3> @@ -29,7 +29,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/@@iterator <h3 id="Using_iterator">Using <code>[@@iterator]()</code></h3> -<pre class="brush:js notranslate">const mySet = new Set(); +<pre class="brush:js">const mySet = new Set(); mySet.add('0'); mySet.add(1); mySet.add({}); @@ -43,7 +43,7 @@ console.log(setIter.next().value); // Object <h3 id="Using_iterator_with_for..of">Using <code>[@@iterator]()</code> with <code>for..of</code></h3> -<pre class="brush:js notranslate">const mySet = new Set(); +<pre class="brush:js">const mySet = new Set(); mySet.add('0'); mySet.add(1); mySet.add({}); diff --git a/files/zh-cn/web/javascript/reference/global_objects/set/@@species/index.html b/files/zh-cn/web/javascript/reference/global_objects/set/@@species/index.html index c950ccbf5a..c8da916aac 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/set/@@species/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/set/@@species/index.html @@ -21,13 +21,13 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/@@species <p>species 属性返回默认的构造函数, 它是<code>Set</code> 对象的构造函数:</p> -<pre class="brush: js notranslate">Set[Symbol.species]; // function Set()</pre> +<pre class="brush: js">Set[Symbol.species]; // function Set()</pre> <h3 id="派生对象中的_Species">派生对象中的 Species</h3> <p>在一个派生集合对象中 (比如你自定义的<code>MySet</code>集合), <code>MySet</code> 的species 属性 是 <code>MySet</code> 构造函数. 又或者, 你想要重写它, 让它能在你派生的类方法中能返回父级<code>Set</code> 对象:</p> -<pre class="brush: js notranslate">class MySet extends Set { +<pre class="brush: js">class MySet extends Set { // Overwrite MySet species to the parent Set constructor static get [Symbol.species]() { return Set; } }</pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/set/add/index.html b/files/zh-cn/web/javascript/reference/global_objects/set/add/index.html index 255379d70c..dac50ccb29 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/set/add/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/set/add/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/add <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code><em>mySet</em>.add(value);</code></pre> +<pre class="syntaxbox"><code><em>mySet</em>.add(value);</code></pre> <h3 id="参数">参数</h3> @@ -37,7 +37,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/add <h2 id="Examples" name="Examples">示例</h2> -<pre class="brush: js notranslate">var mySet = new Set(); +<pre class="brush: js">var mySet = new Set(); mySet.add(1); mySet.add(5).add("some text"); // 可以链式调用 diff --git a/files/zh-cn/web/javascript/reference/global_objects/set/index.html b/files/zh-cn/web/javascript/reference/global_objects/set/index.html index 3e8c53dc64..682edbc181 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/set/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/set/index.html @@ -71,7 +71,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set <h3 id="使用Set对象">使用<code>Set</code>对象</h3> -<pre class="brush: js notranslate">let mySet = new Set(); +<pre class="brush: js">let mySet = new Set(); mySet.add(1); // Set [ 1 ] mySet.add(5); // Set [ 1, 5 ] @@ -102,7 +102,7 @@ console.log(mySet); <h3 id="迭代Set">迭代Set</h3> -<pre class="brush: js notranslate">// 迭代整个set +<pre class="brush: js">// 迭代整个set // 按顺序输出:1, "some text", {"a": 1, "b": 2}, {"a": 1, "b": 2} for (let item of mySet) console.log(item); @@ -147,7 +147,7 @@ mySet.forEach(function(value) { <h3 id="实现基本集合操作">实现基本集合操作</h3> -<pre class="brush: js notranslate">function isSuperset(set, subset) { +<pre class="brush: js">function isSuperset(set, subset) { for (let elem of subset) { if (!set.has(elem)) { return false; @@ -208,7 +208,7 @@ difference(setA, setC); // => Set [1, 2] <h3 id="Array_相关"> <code>Array</code> 相关</h3> -<pre class="brush: js notranslate">let myArray = ["value1", "value2", "value3"]; +<pre class="brush: js">let myArray = ["value1", "value2", "value3"]; // 用Set构造器将Array转换为Set let mySet = new Set(myArray); @@ -221,7 +221,7 @@ console.log([...mySet]); // 与myArray完全一致 <h3 id="数组去重">数组去重</h3> -<pre class="brush: js notranslate">// Use to remove duplicate elements from the array +<pre class="brush: js">// Use to remove duplicate elements from the array const numbers = [2,3,4,4,2,3,3,4,4,5,5,6,6,7,5,32,3,4,5] console.log([...new Set(numbers)]) // [2, 3, 4, 5, 6, 7, 32] @@ -229,7 +229,7 @@ console.log([...new Set(numbers)]) <h3 id="String_相关"><code>String</code> 相关</h3> -<pre class="brush: js notranslate">let text = 'India'; +<pre class="brush: js">let text = 'India'; let mySet = new Set(text); // Set {'I', 'n', 'd', 'i', 'a'} mySet.size; // 5 diff --git a/files/zh-cn/web/javascript/reference/global_objects/set/set/index.html b/files/zh-cn/web/javascript/reference/global_objects/set/set/index.html index a3ae2c0278..7a19f9526a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/set/set/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/set/set/index.html @@ -18,7 +18,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/Set <h2 id="Syntax">Syntax</h2> -<pre class="syntaxbox notranslate">new Set([<var>iterable</var>])</pre> +<pre class="syntaxbox">new Set([<var>iterable</var>])</pre> <h3 id="Parameters">Parameters</h3> @@ -36,7 +36,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/Set <h3 id="Using_the_Set_object">Using the <code>Set</code> object</h3> -<pre class="brush: js notranslate">let mySet = new Set() +<pre class="brush: js">let mySet = new Set() mySet.add(1) // Set [ 1 ] mySet.add(5) // Set [ 1, 5 ] diff --git a/files/zh-cn/web/javascript/reference/global_objects/set/values/index.html b/files/zh-cn/web/javascript/reference/global_objects/set/values/index.html index 846bd7421d..e8a5f552e6 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/set/values/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/set/values/index.html @@ -22,7 +22,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/values <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><em>mySet</em>.values(); +<pre class="syntaxbox"><code><em>mySet</em>.values(); </code></pre> <h3 id="返回值">返回值</h3> @@ -33,7 +33,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Set/values <h3 id="使用_values">使用 <code>values()</code></h3> -<pre class="brush:js notranslate">var mySet = new Set(); +<pre class="brush:js">var mySet = new Set(); mySet.add('foo'); mySet.add('bar'); mySet.add('baz'); diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/charcodeat/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/charcodeat/index.html index 8c683db768..e0c7b1168f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/charcodeat/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/charcodeat/index.html @@ -22,7 +22,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/charCodeAt <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><em>str</em>.charCodeAt(<em>index</em>)</code></pre> +<pre class="syntaxbox"><code><em>str</em>.charCodeAt(<em>index</em>)</code></pre> <h3 id="参数">参数</h3> @@ -55,7 +55,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/charCodeAt <p>下例介绍了不同索引情况下返回的 Unicode 值:</p> -<pre class="brush: js notranslate">"ABC".charCodeAt(0) // returns 65:"A" +<pre class="brush: js">"ABC".charCodeAt(0) // returns 65:"A" "ABC".charCodeAt(1) // returns 66:"B" @@ -67,7 +67,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/charCodeAt <p>这段代码可以被用在 for 循环和其他类似语句中,当在指定引索之前不确定是否有非BMP字符存在时。</p> -<pre class="brush:js notranslate">function fixedCharCodeAt (str, idx) { +<pre class="brush:js">function fixedCharCodeAt (str, idx) { // ex. fixedCharCodeAt ('\uD800\uDC00', 0); // 65536 // ex. fixedCharCodeAt ('\uD800\uDC00', 1); // false idx = idx || 0; @@ -98,7 +98,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/charCodeAt <h3 id="使用_charCodeAt_修复字符串中出现的已知的非BMP字符">使用 <code>charCodeAt()</code> 修复字符串中出现的已知的非BMP字符</h3> -<pre class="brush:js notranslate">function knownCharCodeAt (str, idx) { +<pre class="brush:js">function knownCharCodeAt (str, idx) { str += ''; var code, end = str.length; diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/concat/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/concat/index.html index ee2d8dd06d..7b53403ac2 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/concat/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/concat/index.html @@ -14,7 +14,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/concat <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="notranslate"><code><var>str</var>.concat(<var>str2</var>, [, ...<var>strN</var>])</code></pre> +<pre><code><var>str</var>.concat(<var>str2</var>, [, ...<var>strN</var>])</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -43,7 +43,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/concat <p>下面的例子演示如何将多个字符串与原字符串合并为一个新字符串</p> -<pre class="brush: js notranslate">let hello = 'Hello, ' +<pre class="brush: js">let hello = 'Hello, ' console.log(hello.concat('Kevin', '. Have a nice day.')) // Hello, Kevin. Have a nice day. diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/endswith/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/endswith/index.html index fb6728a8a0..dd5597701e 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/endswith/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/endswith/index.html @@ -23,7 +23,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/endsWith <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>str</var>.endsWith(<var>searchString</var>[, <var>length</var>])</pre> +<pre class="syntaxbox"><var>str</var>.endsWith(<var>searchString</var>[, <var>length</var>])</pre> <h3 id="参数">参数</h3> @@ -46,7 +46,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/endsWith <p>这个方法已经加入到 ECMAScript 6 标准当中,但是可能还没有在所有的 JavaScript 实现中可用。然而,你可以通过如下的代码片段扩展 <code>String.prototype.endsWith()</code> 实现兼容:</p> -<pre class="brush: js notranslate">if (!String.prototype.endsWith) { +<pre class="brush: js">if (!String.prototype.endsWith) { String.prototype.endsWith = function(search, this_len) { if (this_len === undefined || this_len > this.length) { this_len = this.length; @@ -60,7 +60,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/endsWith <h3 id="使用_endsWith">使用 <code>endsWith()</code></h3> -<pre class="brush:js; notranslate">var str = "To be, or not to be, that is the question."; +<pre class="brush:js;">var str = "To be, or not to be, that is the question."; alert( str.endsWith("question.") ); // true alert( str.endsWith("to be") ); // false diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/fromcharcode/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/fromcharcode/index.html index fd399adab7..3ac0a6a122 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/fromcharcode/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/fromcharcode/index.html @@ -16,7 +16,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code>String.fromCharCode(<var>num1</var>[, ...[, <var>numN</var>]])</code></pre> +<pre class="syntaxbox"><code>String.fromCharCode(<var>num1</var>[, ...[, <var>numN</var>]])</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -49,7 +49,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/fromCharCode <p>在 UTF-16 中,BMP 字符使用一个代码单元:</p> -<pre class="brush: js notranslate">String.fromCharCode(65, 66, 67); // 返回 "ABC" +<pre class="brush: js">String.fromCharCode(65, 66, 67); // 返回 "ABC" String.fromCharCode(0x2014); // 返回 "—" String.fromCharCode(0x12014); // 也是返回 "—"; 数字 1 被剔除并忽略 String.fromCharCode(8212); // 也是返回 "—"; 8212 是 0x2014 的十进制表示 @@ -58,7 +58,7 @@ String.fromCharCode(8212); // 也是返回 "—"; 8212 是 0x2014 的十 <p><a href="https://asecuritysite.com/coding/asc2">完整的 UTF 16 表格</a>.<br> 在 UTF-16 中,补充字符需要两个代码单元(即一个代理对):</p> -<pre class="brush: js notranslate">String.fromCharCode(0xD83C, 0xDF03); // Code Point U+1F303 "Night with +<pre class="brush: js">String.fromCharCode(0xD83C, 0xDF03); // Code Point U+1F303 "Night with String.fromCharCode(55356, 57091); // Stars" == "\uD83C\uDF03" String.fromCharCode(0xD834, 0xDF06, 0x61, 0xD834, 0xDF07); // "\uD834\uDF06a\uD834\uDF07" diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/includes/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/includes/index.html index 83ced4b38a..672a34166f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/includes/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/includes/index.html @@ -16,7 +16,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/includes <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><var>str</var>.includes(<var>searchString</var>[, <var>position</var>])</pre> +<pre class="syntaxbox"><var>str</var>.includes(<var>searchString</var>[, <var>position</var>])</pre> <h3 id="参数">参数</h3> @@ -39,13 +39,13 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/includes <p><code>includes()</code> 方法是区分大小写的。例如,下面的表达式会返回 <strong><code>false</code></strong> :</p> -<pre class="notranslate"><code>'Blue Whale'.includes('blue'); // returns false</code></pre> +<pre><code>'Blue Whale'.includes('blue'); // returns false</code></pre> <h2 id="兼容补丁">兼容补丁</h2> <p>这个方法已经被加入到 ECMAScript 6 标准中,但未必在所有的 JavaScript 实现中都可以使用。然而,你可以轻松地 polyfill 这个方法:</p> -<pre class="notranslate"><code>if (!String.prototype.includes) { +<pre><code>if (!String.prototype.includes) { String.prototype.includes = function(search, start) { 'use strict'; if (typeof start !== 'number') { @@ -64,7 +64,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/includes <h3 id="使用_includes">使用 includes()</h3> -<pre class="notranslate"><code>var str = 'To be, or not to be, that is the question.'; +<pre><code>var str = 'To be, or not to be, that is the question.'; console.log(str.includes('To be')); // true console.log(str.includes('question')); // true diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/indexof/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/indexof/index.html index 21434132e5..80213be40f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/indexof/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/indexof/index.html @@ -22,7 +22,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf <h2 id="语法">语法</h2> -<pre class="notranslate"><var>str</var>.indexOf(<var>searchValue [</var>, <var>fromIndex]</var>)</pre> +<pre><var>str</var>.indexOf(<var>searchValue [</var>, <var>fromIndex]</var>)</pre> <h3 id="参数">参数</h3> @@ -43,14 +43,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf <p>若被查找的字符串 <code><var>searchValue</var></code><var> </var>是一个空字符串,将会产生“奇怪”的结果。如果 <code>fromIndex</code> 值为空,或者 <code>fromIndex</code> 值小于被查找的字符串的长度,返回值和以下的 <code>fromIndex</code> 值一样:</p> -<pre class="brush: js notranslate">'hello world'.indexOf('') // 返回 0 +<pre class="brush: js">'hello world'.indexOf('') // 返回 0 'hello world'.indexOf('', 0) // 返回 0 'hello world'.indexOf('', 3) // 返回 3 'hello world'.indexOf('', 8) // 返回 8</pre> <p>另外,如果 <code>fromIndex</code> 值大于等于字符串的长度,将会直接返回字符串的长度(<code>str.length</code>):</p> -<pre class="brush: js notranslate">'hello world'.indexOf('', 11) // 返回 11 +<pre class="brush: js">'hello world'.indexOf('', 11) // 返回 11 'hello world'.indexOf('', 13) // 返回 11 'hello world'.indexOf('', 22) // 返回 11</pre> @@ -60,7 +60,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf <p>字符串中的字符被从左向右索引。第一个字符的索引(index)是 <code>0</code>,变量名为 <code>stringName</code> 的字符串的最后一个字符的索引是 <code>stringName.length - 1</code> 。</p> -<pre class="brush: js notranslate">"Blue Whale".indexOf("Blue") // 返回 0 +<pre class="brush: js">"Blue Whale".indexOf("Blue") // 返回 0 "Blue Whale".indexOf("Blute") // 返回 -1 "Blue Whale".indexOf("Whale", 0) // 返回 5 "Blue Whale".indexOf("Whale", 5) // 返回 5 @@ -71,14 +71,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf <p id="Example_indexOf_and_case-sensitivity"><code>indexOf</code> 方法是区分大小写的。例如,下面的表达式将返回 <code>-1</code>:</p> -<pre class="brush: js notranslate">"Blue Whale".indexOf("blue") // 返回 -1 +<pre class="brush: js">"Blue Whale".indexOf("blue") // 返回 -1 </pre> <h3 id="检测是否存在某字符串">检测是否存在某字符串</h3> <p>注意 <code>0</code> 并不会被当成 <code>true</code> ,<code>-1</code> 不会被当成 <code>false</code> 。所以当检测某个字符串是否存在于另一个字符串中时,可使用下面的方法:</p> -<pre class="notranslate">'Blue Whale'.indexOf('Blue') !== -1 // true +<pre>'Blue Whale'.indexOf('Blue') !== -1 // true 'Blue Whale'.indexOf('Bloe') !== -1 // false ~('Blue Whale'.indexOf('Bloe')) // 0, 这是一种错误用法</pre> @@ -88,7 +88,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/indexOf <p>下例使用 <code>indexOf()</code> 和 <code>lastIndexOf()</code> 方法定位字符串中 "<code>Brave new world</code>" 的值。</p> -<pre class="brush: js notranslate">var anyString = "Brave new world"; +<pre class="brush: js">var anyString = "Brave new world"; console.log("The index of the first w from the beginning is " + anyString.indexOf("w")); // logs 8 @@ -105,7 +105,7 @@ console.log("The index of 'new' from the end is " + anyString.lastIndexOf("new") <p>下例定义了两个字符串变量。两个变量包含相同的字符串,除了第二个字符串中的某些字符为大写。第一个 <code>log</code> 方法输出 19。但是由于 <code>indexOf</code> 方法区分大小写,因此不会在 <code>myCapString</code> 中发现字符串 <code>“cheddar"</code>,所以,第二个 <code>log</code> 方法会输出 -1。</p> -<pre class="brush: js notranslate">var myString = "brie, pepper jack, cheddar"; +<pre class="brush: js">var myString = "brie, pepper jack, cheddar"; var myCapString = "Brie, Pepper Jack, Cheddar"; console.log('myString.indexOf("cheddar") is ' + myString.indexOf("cheddar")); @@ -117,7 +117,7 @@ console.log('myCapString.indexOf("cheddar") is ' + myCapString.indexOf("cheddar" <p>在下例中,设置了 <code>count</code> 来记录字母 <code>e</code> 在字符串 <code>str</code> 中出现的次数:</p> -<pre class="brush: js notranslate">// 翻译:生存还是毁灭?这是个问题。(莎士比亚《哈姆雷特》) +<pre class="brush: js">// 翻译:生存还是毁灭?这是个问题。(莎士比亚《哈姆雷特》) var str = 'To be, or not to be, that is the question.'; var count = 0; var pos = str.indexOf('e'); diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/localecompare/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/localecompare/index.html index 1bdd45c95e..bf0e8ad0fb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/localecompare/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/localecompare/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/localeCompare <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>referenceStr</var>.localeCompare(<var>compareString</var>[, <var>locales</var>[, <var>options</var>]])</code></pre> +<pre class="syntaxbox"><code><var>referenceStr</var>.localeCompare(<var>compareString</var>[, <var>locales</var>[, <var>options</var>]])</code></pre> <h3 id="参数">参数</h3> @@ -90,7 +90,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/localeCompare <h3 id="使用_localeCompare">使用 <code>localeCompare()</code></h3> -<pre class="brush: js notranslate">// The letter "a" is before "c" yielding a negative value +<pre class="brush: js">// The letter "a" is before "c" yielding a negative value 'a'.localeCompare('c'); // -2 or -1 (or some other negative value) @@ -107,7 +107,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/localeCompare <p><code>locales</code> 和 <code>options</code> 参数还没有被所有浏览器所支持。检查是否被支持, 使用 "i" 参数 (a requirement that illegal language tags are rejected) 判断是否有异常 {{jsxref("RangeError")}}抛出:</p> -<pre class="brush: js notranslate">function localeCompareSupportsLocales() { +<pre class="brush: js">function localeCompareSupportsLocales() { try { 'foo'.localeCompare('bar', 'i'); } catch (e) { @@ -121,7 +121,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/localeCompare <p>在不同的语言下 <code>localeCompare()</code> 所提供的结果是不一致的。 为了能让用户得到正确的比较值, 通过使用 <code>locales</code> 参数来提供要比较的语言 (and possibly some fallback languages) :</p> -<pre class="brush: js notranslate">console.log('ä'.localeCompare('z', 'de')); // a negative value: in German, ä sorts with a +<pre class="brush: js">console.log('ä'.localeCompare('z', 'de')); // a negative value: in German, ä sorts with a console.log('ä'.localeCompare('z', 'sv')); // a positive value: in Swedish, ä sorts after z </pre> @@ -129,7 +129,7 @@ console.log('ä'.localeCompare('z', 'sv')); // a positive value: in Swedish, ä <p><code>localeCompare()</code> 所提供的结果可以通过 <code>options</code> 参数来制定:</p> -<pre class="brush: js notranslate">// in German, ä has a as the base letter +<pre class="brush: js">// in German, ä has a as the base letter console.log('ä'.localeCompare('a', 'de', { sensitivity: 'base' })); // 0 // in Swedish, ä and a are separate base letters diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/match/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/match/index.html index cc979f7ffe..5f5b701e63 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/match/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/match/index.html @@ -14,7 +14,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/match <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code><em>str</em>.match(regexp)</code></pre> +<pre class="syntaxbox"><code><em>str</em>.match(regexp)</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -62,7 +62,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/match <p>在下例中,使用 <code>match</code> 查找 "<code>Chapter</code>" 紧跟着 1 个或多个数值字符,再紧跟着一个小数点和数值字符 0 次或多次。正则表达式包含 <code>i</code> 标志,因此大小写会被忽略。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var str = 'For more information, see Chapter 3.4.5.1'; +<pre class="brush: js line-numbers language-js"><code class="language-js">var str = 'For more information, see Chapter 3.4.5.1'; var re = /see (chapter \d+(\.\d)*)/i; var found = str.match(re); @@ -84,7 +84,7 @@ console.log(found); <p>下例展示了 <code>match</code> 使用 global 和 ignore case 标志。A-E、a-e 的所有字母将会作为一个数组的元素返回。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; +<pre class="brush: js line-numbers language-js"><code class="language-js">var str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; var regexp = /[A-E]/gi; var matches_array = str.match(regexp); @@ -93,7 +93,7 @@ console.log(matches_array); <h3 id="使用match,不传参数"><code>使用match(),不传参数 </code></h3> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var str = "Nothing will come of nothing."; +<pre class="brush: js line-numbers language-js"><code class="language-js">var str = "Nothing will come of nothing."; str.match(); // returns [""]</code></pre> @@ -101,7 +101,7 @@ str.match(); // returns [""]</code></pre> <p>当参数是一个字符串或一个数字,它会使用new RegExp(obj)来隐式转换成一个 {{jsxref("RegExp")}}。如果它是一个有正号的正数,RegExp() 方法将忽略正号。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.", +<pre class="brush: js line-numbers language-js"><code class="language-js">var str1 = "NaN means not a number. Infinity contains -Infinity and +Infinity in JavaScript.", str2 = "My grandfather is 65 years old and My grandmother is 63 years old.", str3 = "The contract was declared null and void."; str1.match("number"); // "number" 是字符串。返回["number"] diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html index f2344f6f79..d11d23265e 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/matchall/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/matchAll <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>str</var>.matchAll(<var>regexp</var>)</pre> +<pre class="syntaxbox"><var>str</var>.matchAll(<var>regexp</var>)</pre> <h3 id="参数">参数</h3> @@ -42,7 +42,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/matchAll <p>在 <code>matchAll</code> 出现之前,通过在循环中调用 <code>regexp.exec()</code> 来获取所有匹配项信息(regexp 需使用 <code>/g</code> 标志):</p> -<pre class="brush: js notranslate">const regexp = RegExp('foo[a-z]*','g'); +<pre class="brush: js">const regexp = RegExp('foo[a-z]*','g'); const str = 'table football, foosball'; let match; @@ -54,7 +54,7 @@ while ((match = regexp.exec(str)) !== null) { <p>如果使用 <code>matchAll</code> ,就可以不必使用 while 循环加 exec 方式(且正则表达式需使用 <code>/g</code> 标志)。使用 <code>matchAll</code> 会得到一个迭代器的返回值,配合 <code><a href="/en-US/docs/Web/JavaScript/Reference/Statements/for...of">for...of</a></code>, <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax">array spread</a>, 或者 {{jsxref("Array.from()")}} 可以更方便实现功能:</p> -<pre class="brush: js notranslate">const regexp = RegExp('foo[a-z]*','g'); +<pre class="brush: js">const regexp = RegExp('foo[a-z]*','g'); const str = 'table football, foosball'; const matches = str.matchAll(regexp); @@ -71,14 +71,14 @@ Array.from(str.matchAll(regexp), m => m[0]); <p>如果没有 <code>/g</code> 标志,<code>matchAll</code> 会抛出异常。</p> -<pre class="brush: js notranslate">const regexp = RegExp('[a-c]',''); +<pre class="brush: js">const regexp = RegExp('[a-c]',''); const str = 'abc'; Array.from(str.matchAll(regexp), m => m[0]); // TypeError: String.prototype.matchAll called with a non-global RegExp argument</pre> <p><code>matchAll</code> 内部做了一个 regexp 的复制,所以不像 <a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/exec">regexp.exec</a>, <code>lastIndex</code> 在字符串扫描时不会改变。</p> -<pre class="brush: js notranslate">const regexp = RegExp('[a-c]','g'); +<pre class="brush: js">const regexp = RegExp('[a-c]','g'); regexp.lastIndex = 1; const str = 'abc'; Array.from(str.matchAll(regexp), m => `${regexp.lastIndex} ${m[0]}`); @@ -89,7 +89,7 @@ Array.from(str.matchAll(regexp), m => `${regexp.lastIndex} ${m[0]}`); <p><code>matchAll</code> 的另外一个亮点是更好地获取捕获组。因为当使用 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/match">match()</a></code> 和 <code>/g</code> 标志方式获取匹配信息时,捕获组会被忽略:</p> -<pre class="brush: js notranslate">var regexp = /t(e)(st(\d?))/g; +<pre class="brush: js">var regexp = /t(e)(st(\d?))/g; var str = 'test1test2'; str.match(regexp); @@ -97,7 +97,7 @@ str.match(regexp); <p>使用 <code>matchAll</code> 可以通过如下方式获取分组捕获:</p> -<pre class="brush: js notranslate">let array = [...str.matchAll(regexp)]; +<pre class="brush: js">let array = [...str.matchAll(regexp)]; array[0]; // ['test1', 'e', 'st1', '1', index: 0, input: 'test1test2', length: 4] diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/padend/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/padend/index.html index ca1f5d8515..e73b847c5b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/padend/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/padend/index.html @@ -18,7 +18,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/padEnd <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>str</var>.padEnd(<var>targetLength</var> [, <var>padString</var>])</pre> +<pre class="syntaxbox"><var>str</var>.padEnd(<var>targetLength</var> [, <var>padString</var>])</pre> <h3 id="参数">参数</h3> @@ -35,7 +35,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/padEnd <h2 id="示例">示例</h2> -<pre class="brush: js notranslate">'abc'.padEnd(10); // "abc " +<pre class="brush: js">'abc'.padEnd(10); // "abc " 'abc'.padEnd(10, "foo"); // "abcfoofoof" 'abc'.padEnd(6, "123456"); // "abc123" 'abc'.padEnd(1); // "abc" @@ -45,7 +45,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/padEnd <p>如果原生环境不支持该方法,在其他代码之前先运行下面的代码,将创建 <code>String.prototype.padEnd()</code> 方法。</p> -<pre class="brush: js notranslate">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js +<pre class="brush: js">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padEnd if (!String.prototype.padEnd) { String.prototype.padEnd = function padEnd(targetLength,padString) { diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/padstart/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/padstart/index.html index 8596df0ae3..69aff06b94 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/padstart/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/padstart/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>str</var>.padStart(<var>targetLength</var> [, <var>padString</var>])</pre> +<pre class="syntaxbox"><var>str</var>.padStart(<var>targetLength</var> [, <var>padString</var>])</pre> <h3 id="参数">参数</h3> @@ -37,7 +37,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart <h2 id="示例">示例</h2> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">'abc'.padStart(10); // " abc" +<pre class="brush: js line-numbers language-js"><code class="language-js">'abc'.padStart(10); // " abc" 'abc'.padStart(10, "foo"); // "foofoofabc" 'abc'.padStart(6,"123465"); // "123abc" 'abc'.padStart(8, "0"); // "00000abc" @@ -47,7 +47,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/padStart <p>如果原生环境不支持该方法,在其他代码之前先运行下面的代码,将创建 <code>String.prototype.padStart()</code> 方法。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js +<pre class="brush: js line-numbers language-js"><code class="language-js">// https://github.com/uxitten/polyfill/blob/master/string.polyfill.js // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart if (!String.prototype.padStart) { String.prototype.padStart = function padStart(targetLength,padString) { diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/repeat/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/repeat/index.html index b880c16b92..c0ee77fe21 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/repeat/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/repeat/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code><var>str</var>.repeat(<var>count</var>)</code></pre> +<pre class="syntaxbox"><code><var>str</var>.repeat(<var>count</var>)</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -44,7 +44,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat <p>此方法已添加到 ECMAScript 2015 规范中,并且可能尚未在所有 JavaScript 实现中可用。然而,你可以使用以下代码段对 String.prototype.repeat() 进行填充:</p> -<pre class="brush: js language-js notranslate"><code class="language-js">if (!String.prototype.repeat) { +<pre class="brush: js language-js"><code class="language-js">if (!String.prototype.repeat) { String.prototype.repeat = function(count) { 'use strict'; if (this == null) { @@ -88,7 +88,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/repeat <h2 id="Examples" name="Examples">示例</h2> -<pre class="brush:js notranslate">"abc".repeat(-1) // RangeError: repeat count must be positive and less than inifinity +<pre class="brush:js">"abc".repeat(-1) // RangeError: repeat count must be positive and less than inifinity "abc".repeat(0) // "" "abc".repeat(1) // "abc" "abc".repeat(2) // "abcabc" diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/replace/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/replace/index.html index 49f27efe4b..5991e8fa0a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/replace/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/replace/index.html @@ -21,7 +21,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/replace <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>str</var>.replace(<var>regexp</var>|<var>substr</var>, <var>newSubStr</var>|<var>function</var>)</code></pre> +<pre class="syntaxbox"><code><var>str</var>.replace(<var>regexp</var>|<var>substr</var>, <var>newSubStr</var>|<var>function</var>)</code></pre> <h3 id="参数">参数</h3> @@ -137,7 +137,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/replace <p>下面的例子将会使 <code>newString</code> 变成 <code>'abc - 12345 - #$*%'</code>:</p> -<pre class="brush: js notranslate">function replacer(match, p1, p2, p3, offset, string) { +<pre class="brush: js">function replacer(match, p1, p2, p3, offset, string) { // p1 is nondigits, p2 digits, and p3 non-alphanumerics return [p1, p2, p3].join(' - '); } @@ -151,7 +151,7 @@ console.log(newString); // abc - 12345 - #$*% <p>在下面的例子中,<code>replace()</code> 中使用了正则表达式及忽略大小写标示。</p> -<pre class="brush: js notranslate">var str = 'Twas the night before Xmas...'; +<pre class="brush: js">var str = 'Twas the night before Xmas...'; var newstr = str.replace(/xmas/i, 'Christmas'); console.log(newstr); // Twas the night before Christmas... </pre> @@ -160,7 +160,7 @@ console.log(newstr); // Twas the night before Christmas... <p>下面的例子中,正则表达式包含有全局替换(g)和忽略大小写(i)的选项,这使得replace方法用'oranges'替换掉了所有出现的"apples".</p> -<pre class="brush: js notranslate">var re = /apples/gi; +<pre class="brush: js">var re = /apples/gi; var str = "Apples are round, and apples are juicy."; var newstr = str.replace(re, "oranges"); @@ -172,7 +172,7 @@ console.log(newstr); <p>下面的例子演示了如何交换一个字符串中两个单词的位置,这个脚本使用$1 和 $2 代替替换文本。</p> -<pre class="brush: js notranslate">var re = /(\w+)\s(\w+)/; +<pre class="brush: js">var re = /(\w+)\s(\w+)/; var str = "John Smith"; var newstr = str.replace(re, "$2, $1"); // Smith, John @@ -185,7 +185,7 @@ console.log(newstr); <p>在返回前,替换函数允许匹配片段作为参数,并且将它和连字符进行连接作为新的片段。</p> -<pre class="brush: js notranslate">function styleHyphenFormat(propertyName) { +<pre class="brush: js">function styleHyphenFormat(propertyName) { function upperToHyphenLower(match) { return '-' + match.toLowerCase(); } @@ -197,7 +197,7 @@ console.log(newstr); <p>因为我们想在最终的替换中进一步转变匹配结果,所以我们必须使用一个函数。这迫使我们在使用{{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}}方法前进行评估。如果我们尝试不用一个函数进行匹配,那么使用{{jsxref("String.prototype.toLowerCase()", "toLowerCase()")}} 方法将不会有效。</p> -<pre class="brush: js notranslate">var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase()); // won't work +<pre class="brush: js">var newString = propertyName.replace(/[A-Z]/g, '-' + '$&'.toLowerCase()); // won't work </pre> <p>这是因为 <code>'$&'.toLowerCase()</code> 会先被解析成字符串字面量(这会导致相同的'$&')而不是当作一个模式。</p> @@ -208,7 +208,7 @@ console.log(newstr); <p>正则表达式test检查任何数字是否以 F 结尾。华氏温度通过第二个参数p1进入函数。这个函数基于华氏温度作为字符串传递给f2c函数设置成摄氏温度。然后f2c()返回摄氏温度。这个函数与Perl的 s///e 标志相似。</p> -<pre class="brush: js notranslate">function f2c(x) +<pre class="brush: js">function f2c(x) { function convert(str, p1, offset, s) { @@ -227,7 +227,7 @@ console.log(newstr); <p><strong>输入:</strong><br> 一个由 x,- 和 _ 组成的字符串。</p> -<pre class="notranslate">x-x_ +<pre>x-x_ ---x---x---x--- @@ -240,7 +240,7 @@ _x_x___x___x___ <p>一个数组对象。'x' 产生一个 'on' 状态,'-'(连接符)产生一个 'off' 状态,而 '_' (下划线)表示 'on' 状态的长度。</p> -<pre class="brush: js notranslate">[ +<pre class="brush: js">[ { on: true, length: 1 }, { on: false, length: 1 }, { on: true, length: 2 } @@ -249,7 +249,7 @@ _x_x___x___x___ <p>代码片段:</p> -<pre class="brush: js notranslate">var str = 'x-x_'; +<pre class="brush: js">var str = 'x-x_'; var retArr = []; str.replace(/(x_*)|(-)/g, function(match, p1, p2) { if (p1) { retArr.push({ on: true, length: p1.length }); } diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/replaceall/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/replaceall/index.html index cbd76d71b7..c9d892e3f7 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/replaceall/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/replaceall/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/replaceAll <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">const newStr = <var>str</var>.replaceAll(<var>regexp</var>|<var>substr</var>, <var>newSubstr</var>|<var>function</var>)</pre> +<pre class="syntaxbox">const newStr = <var>str</var>.replaceAll(<var>regexp</var>|<var>substr</var>, <var>newSubstr</var>|<var>function</var>)</pre> <div class="blockIndicator note"> <p>当使用一个 `regex`时,您必须设置全局(“ g”)标志,<br> @@ -123,20 +123,20 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/replaceAll <h3 id="使用_replaceAll">使用 replaceAll</h3> -<pre class="brush: js notranslate">'aabbcc'.replaceAll('b', '.'); +<pre class="brush: js">'aabbcc'.replaceAll('b', '.'); // 'aa..cc'</pre> <h3 id="非全局_regex_抛出">非全局 regex 抛出</h3> <p>使用正则表达式搜索值时,它必须是全局的。这将行不通:</p> -<pre class="brush: js; example-bad notranslate">'aabbcc'.replaceAll(/b/, '.'); +<pre class="brush: js; example-bad">'aabbcc'.replaceAll(/b/, '.'); TypeError: replaceAll must be called with a global RegExp </pre> <p>这将可以正常运行:</p> -<pre class="brush: js; example-good notranslate">'aabbcc'.replaceAll(/b/g, '.'); +<pre class="brush: js; example-good">'aabbcc'.replaceAll(/b/g, '.'); "aa..cc" </pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/search/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/search/index.html index 06c7e214fd..35a75549c2 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/search/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/search/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/search <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>str</var>.search(<var>regexp</var>)</pre> +<pre class="syntaxbox"><var>str</var>.search(<var>regexp</var>)</pre> <h3 id="参数">参数</h3> @@ -44,7 +44,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/search <p>下面的例子中用两个不同的正则表达式对同一个字符串执行搜索匹配,得到一个成功匹配(正数返回值)和一个失败匹配(-1)。</p> -<pre class="brush: js notranslate">var str = "hey JudE"; +<pre class="brush: js">var str = "hey JudE"; var re = /[A-Z]/g; var re2 = /[.]/g; console.log(str.search(re)); // returns 4, which is the index of the first capital letter "J" diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/startswith/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/startswith/index.html index 7cbd48ba7b..ac60af390f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/startswith/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/startswith/index.html @@ -21,7 +21,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>str</var>.startsWith(<var>searchString</var>[, <var>position</var>])</pre> +<pre class="syntaxbox"><var>str</var>.startsWith(<var>searchString</var>[, <var>position</var>])</pre> <h3 id="参数">参数</h3> @@ -44,7 +44,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith <p>此方法已被添加至 ECMAScript 2015 规范之中,但可能不能在所有的现行 JavaScript 实现中使用。不过,你可以用以下的代码段为 <code>String.prototype.startsWith()</code> 制作 Polyfill:</p> -<pre class="brush: js notranslate">if (!String.prototype.startsWith) { +<pre class="brush: js">if (!String.prototype.startsWith) { Object.defineProperty(String.prototype, 'startsWith', { value: function(search, pos) { pos = !pos || pos < 0 ? 0 : +pos; @@ -60,7 +60,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/startsWith <h3 id="使用_startsWith">使用 <code>startsWith()</code></h3> -<pre class="brush:js; notranslate">var str = "To be, or not to be, that is the question."; +<pre class="brush:js;">var str = "To be, or not to be, that is the question."; alert(str.startsWith("To be")); // true alert(str.startsWith("not to be")); // false diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/substring/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/substring/index.html index e2b061d1a3..f35badbe86 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/substring/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/substring/index.html @@ -11,7 +11,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/substring <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code><var>str</var>.substring(<var>indexStart</var>[, <var>indexEnd</var>])</code></pre> +<pre class="syntaxbox"><code><var>str</var>.substring(<var>indexStart</var>[, <var>indexEnd</var>])</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -44,7 +44,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/substring <p>下例使用 <code>substring</code> 输出字符串 "<code>Mozilla</code>" 中的字符:</p> -<pre class="brush:js notranslate">var anyString = "Mozilla"; +<pre class="brush:js">var anyString = "Mozilla"; // 输出 "Moz" console.log(anyString.substring(0,3)); @@ -73,7 +73,7 @@ console.log(anyString.substring(0,10)); <p>下面一个例子运用了 String.length 属性去获取指定字符串的倒数元素。显然这个办法更容易记住,因为你不再像上面那个例子那样去记住起始位置和最终位置。</p> -<pre class="brush: js notranslate"><code>// Displays 'illa' the last 4 characters +<pre class="brush: js"><code>// Displays 'illa' the last 4 characters var anyString = 'Mozilla'; var anyString4 = anyString.substring(anyString.length - 4); console.log(anyString4);</code> @@ -87,7 +87,7 @@ console.log(anyString5);</pre> <p>下例替换了一个字符串中的子字符串。可以替换单个字符和子字符串。该例结尾调用的函数将 "<code>Brave New World</code>" 变成了 "<code>Brave New Web</code>"。</p> -<pre class="brush:js notranslate">function replaceString(oldS, newS, fullS) { +<pre class="brush:js">function replaceString(oldS, newS, fullS) { // Replaces oldS with newS in the string fullS for (var i = 0; i < fullS.length; i++) { if (fullS.substring(i, i + oldS.length) == oldS) { @@ -101,7 +101,7 @@ replaceString("World", "Web", "Brave New World");</pre> <p>需要注意的是,如果 <code>oldS</code> 是 <code>newS</code> 的子字符串将会导致死循环。例如,尝试把 "Web" 替换成 "OtherWorld"。一个更好的方法如下:</p> -<pre class="brush:js notranslate">function replaceString(oldS, newS,fullS){ +<pre class="brush:js">function replaceString(oldS, newS,fullS){ return fullS.split(oldS).join(newS); }</pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/tolowercase/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/tolowercase/index.html index 007d9bb2d9..b1b9f6266d 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/tolowercase/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/tolowercase/index.html @@ -15,7 +15,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase <h2 id="语法" style="margin-bottom: 20px; line-height: 30px;">语法</h2> -<pre class="syntaxbox language-html notranslate" style="margin-bottom: 0px; padding: 1em; border-left-width: 6px; border-left-style: solid; font-family: Consolas, Monaco, 'Andale Mono', monospace; font-size: 14px; direction: ltr; white-space: normal; text-shadow: none; background-color: rgba(212, 221, 228, 0.498039);"><code class="language-html" style="font-family: Consolas, Monaco, 'Andale Mono', monospace; direction: ltr; color: inherit; text-shadow: none;">str.toLowerCase()</code> +<pre class="syntaxbox language-html" style="margin-bottom: 0px; padding: 1em; border-left-width: 6px; border-left-style: solid; font-family: Consolas, Monaco, 'Andale Mono', monospace; font-size: 14px; direction: ltr; white-space: normal; text-shadow: none; background-color: rgba(212, 221, 228, 0.498039);"><code class="language-html" style="font-family: Consolas, Monaco, 'Andale Mono', monospace; direction: ltr; color: inherit; text-shadow: none;">str.toLowerCase()</code> </pre> <p id="sect1"></p> @@ -32,7 +32,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/toLowerCase <h3 id="例子:使用_toLowerCase" style="line-height: 24px;">例子:使用 <code>toLowerCase()</code></h3> -<pre class="brush: js notranslate">console.log('中文简体 zh-CN || zh-Hans'.toLowerCase()); +<pre class="brush: js">console.log('中文简体 zh-CN || zh-Hans'.toLowerCase()); // 中文简体 zh-cn || zh-hans console.log( "ALPHABET".toLowerCase() ); diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/touppercase/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/touppercase/index.html index 0e45f82bac..820f1a80b3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/touppercase/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/touppercase/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>str</var>.toUpperCase()</pre> +<pre class="syntaxbox"><var>str</var>.toUpperCase()</pre> <h3 id="返回值">返回值</h3> @@ -40,14 +40,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/toUpperCase <h3 id="基本用法">基本用法</h3> -<pre class="brush: js notranslate">console.log('alphabet'.toUpperCase()); // 'ALPHABET' +<pre class="brush: js">console.log('alphabet'.toUpperCase()); // 'ALPHABET' </pre> <h3 id="将非字符串类型的_this_(上下文)转为字符串">将非字符串类型的 <code>this</code> (上下文)转为字符串</h3> <p>此方法会将任何非字符串类型的值转为字符串, 当你将其上下文 <code>this</code> 值设置为非字符串类型</p> -<pre class="brush: js notranslate">const a = String.prototype.toUpperCase.call({ +<pre class="brush: js">const a = String.prototype.toUpperCase.call({ toString: function toString() { return 'abcdef'; } diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html index 503a9e234f..aa0e524f53 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/trim/index.html @@ -26,7 +26,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>str</var>.trim()</code></pre> +<pre class="syntaxbox"><code><var>str</var>.trim()</code></pre> <h3 id="返回值">返回值</h3> @@ -42,7 +42,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/Trim <p>下面的例子中将显示小写的字符串 'foo':</p> -<pre class="brush: js notranslate">var orig = ' foo '; +<pre class="brush: js">var orig = ' foo '; console.log(orig.trim()); // 'foo' // 另一个 .trim() 例子,只从一边删除 @@ -55,7 +55,7 @@ console.log(orig.trim()); // 'foo' <p>如果 <code>trim()</code> 不存在,可以在所有代码前执行下面代码</p> -<pre class="brush: js notranslate">if (!String.prototype.trim) { +<pre class="brush: js">if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, ''); }; diff --git a/files/zh-cn/web/javascript/reference/global_objects/string/valueof/index.html b/files/zh-cn/web/javascript/reference/global_objects/string/valueof/index.html index 6af5bd5d2d..2d8754a2cc 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/string/valueof/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/string/valueof/index.html @@ -11,7 +11,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/valueOf <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>str</var>.valueOf()</code></pre> +<pre class="syntaxbox"><code><var>str</var>.valueOf()</code></pre> <h3 id="返回结果">返回结果</h3> @@ -27,7 +27,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/String/valueOf <h3 id="使用_valueOf">使用 <code>valueOf()</code></h3> -<pre class="brush: js notranslate">var x = new String('Hello world'); +<pre class="brush: js">var x = new String('Hello world'); console.log(x.valueOf()); // Displays 'Hello world' </pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/symbol/hasinstance/index.html b/files/zh-cn/web/javascript/reference/global_objects/symbol/hasinstance/index.html index 2381f6654f..c4d2d0753a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/symbol/hasinstance/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/symbol/hasinstance/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/hasInstance <p>你可实现一个自定义的<code>instanceof</code> 行为,例如:</p> -<pre class="brush: js notranslate">class MyArray { +<pre class="brush: js">class MyArray { static [Symbol.hasInstance](instance) { return Array.isArray(instance); } diff --git a/files/zh-cn/web/javascript/reference/global_objects/symbol/index.html b/files/zh-cn/web/javascript/reference/global_objects/symbol/index.html index 5e23754b25..9473363551 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/symbol/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/symbol/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Symbol <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><code>Symbol(<em>[description]</em>)</code></pre> +<pre class="syntaxbox"><code>Symbol(<em>[description]</em>)</code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -32,24 +32,24 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Symbol <p>直接使用<code>Symbol()</code>创建新的symbol类型,并用一个可选的字符串作为其描述。</p> -<pre class="brush: js notranslate">var sym1 = Symbol(); +<pre class="brush: js">var sym1 = Symbol(); var sym2 = Symbol('foo'); var sym3 = Symbol('foo'); </pre> <p>上面的代码创建了三个新的symbol类型。 注意,<code>Symbol("foo")</code> 不会强制将字符串 “foo” 转换成symbol类型。它每次都会创建一个新的 symbol类型:</p> -<pre class="brush: js notranslate">Symbol("foo") === Symbol("foo"); // false</pre> +<pre class="brush: js">Symbol("foo") === Symbol("foo"); // false</pre> <p>下面带有 {{jsxref("Operators/new", "new")}} 运算符的语法将抛出 {{jsxref("TypeError")}} 错误:</p> -<pre class="brush: js notranslate">var sym = new Symbol(); // TypeError</pre> +<pre class="brush: js">var sym = new Symbol(); // TypeError</pre> <p>这会阻止创建一个显式的 Symbol 包装器对象而不是一个 Symbol 值。围绕原始数据类型创建一个显式包装器对象从 ECMAScript 6 开始不再被支持。 然而,现有的原始包装器对象,如 <code style="font-style: normal;">new Boolean</code>、<code style="font-style: normal;">new String</code>以及<code>new Number</code>,因为遗留原因仍可被创建。</p> <p>如果你真的想创建一个 <u>Symbol 包装器对象 </u>(<code>Symbol wrapper object</code>),你可以使用 <code>Object()</code> 函数:</p> -<pre class="brush: js notranslate">var sym = Symbol("foo"); +<pre class="brush: js">var sym = Symbol("foo"); typeof sym; // "symbol" var symObj = Object(sym); typeof symObj; // "object"</pre> @@ -150,7 +150,7 @@ typeof symObj; // "object"</pre> <p> {{jsxref("Operators/typeof", "typeof")}}运算符能帮助你识别 symbol 类型</p> -<pre class="brush: js notranslate"><code class="language-js">typeof Symbol() === 'symbol' +<pre class="brush: js"><code class="language-js">typeof Symbol() === 'symbol' typeof Symbol('foo') === 'symbol' typeof Symbol.iterator === 'symbol'</code> </pre> @@ -170,7 +170,7 @@ typeof Symbol.iterator === 'symbol'</code> <p>Symbols 在 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in"><code>for...in</code></a> 迭代中不可枚举。另外,{{jsxref("Object.getOwnPropertyNames()")}} 不会返回 symbol 对象的属性,但是你能使用 {{jsxref("Object.getOwnPropertySymbols()")}} 得到它们。</p> -<pre class="brush: js line-numbers language-js notranslate"><code class="language-js">var obj = {}; +<pre class="brush: js line-numbers language-js"><code class="language-js">var obj = {}; obj[Symbol("a")] = "a"; obj[Symbol.for("b")] = "b"; @@ -185,7 +185,7 @@ for (var i in obj) { <p>当使用 JSON.stringify() 时,以 symbol 值作为键的属性会被完全忽略:</p> -<pre class="brush: js notranslate"><code class="language-js">JSON.stringify({[Symbol("foo")]: "foo"}); +<pre class="brush: js"><code class="language-js">JSON.stringify({[Symbol("foo")]: "foo"}); // '{}'</code></pre> <p>更多细节,请看 {{jsxref("JSON.stringify()")}}。</p> @@ -194,7 +194,7 @@ for (var i in obj) { <p>当一个 Symbol 包装器对象作为一个属性的键时,这个对象将被强制转换为它包装过的 symbol 值:</p> -<pre class="brush: js notranslate"><code class="language-js">var sym = Symbol("foo"); +<pre class="brush: js"><code class="language-js">var sym = Symbol("foo"); var obj = {[sym]: 1}; obj[sym]; // 1 obj[Object(sym)]; // still 1</code></pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/symbol/keyfor/index.html b/files/zh-cn/web/javascript/reference/global_objects/symbol/keyfor/index.html index 150ae66f02..c38fa9307b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/symbol/keyfor/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/symbol/keyfor/index.html @@ -11,7 +11,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/keyFor <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><var>Symbol.keyFor(sym)</var>;</pre> +<pre class="syntaxbox"><var>Symbol.keyFor(sym)</var>;</pre> <h3 id="参数">参数</h3> @@ -28,7 +28,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/keyFor <h2 id="示例">示例</h2> -<pre class="brush: js notranslate">// 创建一个全局 Symbol +<pre class="brush: js">// 创建一个全局 Symbol var globalSym = Symbol.for("foo"); Symbol.keyFor(globalSym); // "foo" diff --git a/files/zh-cn/web/javascript/reference/global_objects/symbol/search/index.html b/files/zh-cn/web/javascript/reference/global_objects/symbol/search/index.html index c1efdd302e..f3d595a2fb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/symbol/search/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/symbol/search/index.html @@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/search <h3 id="自定义字符串搜索">自定义字符串搜索</h3> -<pre class="notranslate">class caseInsensitiveSearch { +<pre>class caseInsensitiveSearch { constructor(value) { this.value = value.toLowerCase(); } diff --git a/files/zh-cn/web/javascript/reference/global_objects/symbol/split/index.html b/files/zh-cn/web/javascript/reference/global_objects/symbol/split/index.html index 53b98d57cd..221254014b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/symbol/split/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/symbol/split/index.html @@ -19,11 +19,11 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Symbol/split <p>[Symbol.split]指向‘aba’.split(/a/)</p> -<pre class="brush: js notranslate">/a/[Symbol.split]('aba',3)</pre> +<pre class="brush: js">/a/[Symbol.split]('aba',3)</pre> <p>"dayinlove".split(exp)调用[Symbol.split](str)处理,并把实参"dayinlove"传给形参str</p> -<pre class="brush: js notranslate">var exp = { +<pre class="brush: js">var exp = { pat:'in', [Symbol.split](str) { return str.split(this.pat); diff --git a/files/zh-cn/web/javascript/reference/global_objects/typedarray/foreach/index.html b/files/zh-cn/web/javascript/reference/global_objects/typedarray/foreach/index.html index 801df8bed5..b88d1af965 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/typedarray/foreach/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/typedarray/foreach/index.html @@ -9,7 +9,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/forEach <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>typedarray</var>.forEach(<var>callback</var>[, <var>thisArg</var>])</code></pre> +<pre class="syntaxbox"><code><var>typedarray</var>.forEach(<var>callback</var>[, <var>thisArg</var>])</code></pre> <h3 id="参数">参数</h3> @@ -57,7 +57,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/forEach <p>下面的代码为数组中的每个元素记录一行日志:</p> -<pre class="brush:js notranslate">function logArrayElements(element, index, array) { +<pre class="brush:js">function logArrayElements(element, index, array) { console.log('a[' + index + '] = ' + element); } diff --git a/files/zh-cn/web/javascript/reference/global_objects/typedarray/set/index.html b/files/zh-cn/web/javascript/reference/global_objects/typedarray/set/index.html index 3ba2095fbf..44e1793347 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/typedarray/set/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/typedarray/set/index.html @@ -9,7 +9,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/set <h2 id="语法">语法</h2> -<pre class="notranslate"><var>typedarray</var>.set(<em>array</em>[, <em>offset</em>]) +<pre><var>typedarray</var>.set(<em>array</em>[, <em>offset</em>]) <em>typedarray</em>.set(<em>typedarray</em>[, <em>offset</em>])</pre> <h3 id="参数">参数</h3> @@ -35,7 +35,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/TypedArray/set <h3 id="使用_set">使用 <code>set()</code></h3> -<pre class="brush:js notranslate">var buffer = new ArrayBuffer(8); +<pre class="brush:js">var buffer = new ArrayBuffer(8); var uint8 = new Uint8Array(buffer); uint8.set([1,2,3], 3); diff --git a/files/zh-cn/web/javascript/reference/global_objects/uint16array/index.html b/files/zh-cn/web/javascript/reference/global_objects/uint16array/index.html index 9479c4831e..62adba345b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/uint16array/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/uint16array/index.html @@ -106,7 +106,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Uint16Array <h3 id="Different_ways_to_create_a_Uint16Array">Different ways to create a Uint16Array</h3> -<pre class="brush: js notranslate">// 长度 +<pre class="brush: js">// 长度 var uint16 = new Uint16Array(2); uint16[0] = 42; console.log(uint16[0]); // 42 diff --git a/files/zh-cn/web/javascript/reference/global_objects/uint8clampedarray/index.html b/files/zh-cn/web/javascript/reference/global_objects/uint8clampedarray/index.html index 86028a8fb9..d4a018398c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/uint8clampedarray/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/uint8clampedarray/index.html @@ -9,7 +9,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">new Uint8ClampedArray(length); +<pre class="syntaxbox">new Uint8ClampedArray(length); new Uint8ClampedArray(typedArray); new Uint8ClampedArray(object); new Uint8ClampedArray(buffer [, byteOffset [, length]]);</pre> @@ -120,7 +120,7 @@ new Uint8ClampedArray(buffer [, byteOffset [, length]]);</pre> <p>创建一个 <code>Uint8ClampedArray</code> 的不同方式:</p> -<pre class="brush: js notranslate">// From a length +<pre class="brush: js">// From a length var uintc8 = new Uint8ClampedArray(2); uintc8[0] = 42; uintc8[1] = 1337; @@ -265,11 +265,11 @@ var uintc8 = new Uint8ClampedArray(iterable); <p>从 ECMAScript 2015 开始, <code>Uint8ClampedArray</code> 构造函数需要用一个 {{jsxref("Operators/new", "new")}} 操作符来构建。从现在开始,不使用 <code>new</code> 来调用一个 <code>Uint8ClampedArray</code> 构造函数将会抛出一个 {{jsxref("TypeError")}}。</p> -<pre class="brush: js example-bad notranslate">var dv = Uint8ClampedArray([1, 2, 3]); +<pre class="brush: js example-bad">var dv = Uint8ClampedArray([1, 2, 3]); // TypeError: calling a builtin Uint8ClampedArray constructor // without new is forbidden</pre> -<pre class="brush: js example-good notranslate">var dv = new Uint8ClampedArray([1, 2, 3]);</pre> +<pre class="brush: js example-good">var dv = new Uint8ClampedArray([1, 2, 3]);</pre> <h2 id="参见">参见</h2> diff --git a/files/zh-cn/web/javascript/reference/global_objects/unescape/index.html b/files/zh-cn/web/javascript/reference/global_objects/unescape/index.html index 4577d2f5cc..85746f1bc3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/unescape/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/unescape/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/unescape <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code>unescape(str)</code></pre> +<pre class="syntaxbox"><code>unescape(str)</code></pre> <h3 id="参数">参数</h3> @@ -32,7 +32,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/unescape <h2 id="示例">示例</h2> -<pre class="brush: js notranslate">unescape('abc123'); // "abc123" +<pre class="brush: js">unescape('abc123'); // "abc123" unescape('%E4%F6%FC'); // "äöü" unescape('%u0107'); // "ć" </pre> diff --git a/files/zh-cn/web/javascript/reference/global_objects/weakref/deref/index.html b/files/zh-cn/web/javascript/reference/global_objects/weakref/deref/index.html index 9d9fdbdba1..2d4cf7f3b6 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/weakref/deref/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/weakref/deref/index.html @@ -11,7 +11,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/WeakRef/deref <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>obj</var> = <var>ref</var>.deref();</code> +<pre class="syntaxbox"><code><var>obj</var> = <var>ref</var>.deref();</code> </pre> <h3 id="返回值">返回值</h3> @@ -28,7 +28,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/WeakRef/deref <p>有关<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef#Examples">完整示例</a>,请参阅{{jsxref("WeakRef")}}页面的示例部分。</p> -<pre class="brush: js notranslate">const tick = () => { +<pre class="brush: js">const tick = () => { // Get the element from the weak reference, if it still exists const element = this.ref.deref(); if (element) { diff --git a/files/zh-cn/web/javascript/reference/global_objects/weakref/index.html b/files/zh-cn/web/javascript/reference/global_objects/weakref/index.html index 91452cd75f..9f9f275816 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/weakref/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/weakref/index.html @@ -68,7 +68,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/WeakRef <p>这个例子演示了在一个DOM元素中启动一个计数器,当这个元素不存在时停止:</p> -<pre class="brush: js notranslate">class Counter { +<pre class="brush: js">class Counter { constructor(element) { // Remember a weak reference to the DOM element this.ref = new WeakRef(element); diff --git a/files/zh-cn/web/javascript/reference/global_objects/webassembly/global/index.html b/files/zh-cn/web/javascript/reference/global_objects/webassembly/global/index.html index 3366032120..d8577bae83 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/webassembly/global/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/webassembly/global/index.html @@ -43,7 +43,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Global <p>global的值发生改变, 首先设置<code>Global.value</code> 为42, 然后使用导出函数 <code>incGlobal()</code> 增加为43. 导出函数在 <code>global.wasm</code> 模块中(它将参数的值加一并返回).</p> -<pre class="brush: js notranslate">const output = document.getElementById('output'); +<pre class="brush: js">const output = document.getElementById('output'); function assertEq(msg, got, expected) { output.innerHTML += `Testing ${msg}: `; diff --git a/files/zh-cn/web/javascript/reference/global_objects/webassembly/instance/index.html b/files/zh-cn/web/javascript/reference/global_objects/webassembly/instance/index.html index 44dec6610b..de15cec004 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/webassembly/instance/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/webassembly/instance/index.html @@ -21,7 +21,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Instance <p><strong>重要</strong>: 由于大型模块的实例化代价极高, 开发人员应只在必须同步实例化的时候,才使用<code>Instance()</code>;绝大多数情况应该使用异步方法{{jsxref("WebAssembly.instantiate()")}} .</p> </div> -<pre class="syntaxbox notranslate">var myInstance = new WebAssembly.Instance(<em>module</em>, <em>importObject</em>);</pre> +<pre class="syntaxbox">var myInstance = new WebAssembly.Instance(<em>module</em>, <em>importObject</em>);</pre> <h3 id="参数">参数</h3> diff --git a/files/zh-cn/web/javascript/reference/global_objects/webassembly/table/index.html b/files/zh-cn/web/javascript/reference/global_objects/webassembly/table/index.html index 9582758e32..9be0f967cd 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/webassembly/table/index.html +++ b/files/zh-cn/web/javascript/reference/global_objects/webassembly/table/index.html @@ -15,7 +15,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Table <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">var myTable = new WebAssembly.Table(tableDescriptor);</pre> +<pre class="syntaxbox">var myTable = new WebAssembly.Table(tableDescriptor);</pre> <h3 id="参数">参数</h3> @@ -68,14 +68,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/WebAssembly/Table <p>The following example (see table2.html <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/table2.html">source code</a> and <a href="https://mdn.github.io/webassembly-examples/js-api-examples/table2.html">live version</a>) creates a new WebAssembly Table instance with an initial size of 2 elements. We then print out the table length and contents of the two indexes (retrieved via {{jsxref("WebAssembly/Table/get", "Table.prototype.get()")}} to show that the length is two and both elements are {{jsxref("null")}}.</p> -<pre class="brush: js notranslate">var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"}); +<pre class="brush: js">var tbl = new WebAssembly.Table({initial:2, element:"anyfunc"}); console.log(tbl.length); // "2" console.log(tbl.get(0)); // "null" console.log(tbl.get(1)); // "null"</pre> <p>We then create an import object that contains the table:</p> -<pre class="brush: js notranslate">var importObj = { +<pre class="brush: js">var importObj = { js: { tbl:tbl } @@ -83,7 +83,7 @@ console.log(tbl.get(1)); // "null"</pre> <p>Finally, we load and instantiate a wasm module (table2.wasm) using the {{jsxref("WebAssembly.instantiateStreaming()")}} method. The table2.wasm module contains two functions (one that returns 42 and another that returns 83) and stores both into elements 0 and 1 of the imported table (see <a href="https://github.com/mdn/webassembly-examples/blob/master/js-api-examples/table2.wat">text representation</a>). So after instantiation, the table still has length 2, but the elements now contain callable <a href="/en-US/docs/WebAssembly/Exported_functions">Exported WebAssembly Functions</a> which we can call from JS.</p> -<pre class="brush: js notranslate">WebAssembly.instantiateStreaming(fetch('table2.wasm'), importObject) +<pre class="brush: js">WebAssembly.instantiateStreaming(fetch('table2.wasm'), importObject) .then(function(obj) { console.log(tbl.length); console.log(tbl.get(0)()); diff --git a/files/zh-cn/web/javascript/reference/iteration_protocols/index.html b/files/zh-cn/web/javascript/reference/iteration_protocols/index.html index 975c55a7fe..d55dfd4111 100644 --- a/files/zh-cn/web/javascript/reference/iteration_protocols/index.html +++ b/files/zh-cn/web/javascript/reference/iteration_protocols/index.html @@ -84,7 +84,7 @@ translation_of: Web/JavaScript/Reference/Iteration_protocols <p>这样做允许一个迭代器能被各种需要可迭代对象的语法所使用。因此,很少会只实现迭代器协议,而不实现可迭代协议。</p> -<pre class="brush: js example-good notranslate"><code>var myIterator = { +<pre class="brush: js example-good"><code>var myIterator = { next: function() { // ... }, @@ -96,13 +96,13 @@ translation_of: Web/JavaScript/Reference/Iteration_protocols <p>{{jsxref("String")}} 是一个内置的可迭代对象:</p> -<pre class="brush: js notranslate">let someString = "hi"; +<pre class="brush: js">let someString = "hi"; typeof someString[Symbol.iterator]; // "function" </pre> <p><code>String</code> 的默认迭代器会依次返回该字符串的各码点(code point):</p> -<pre class="brush: js notranslate">let iterator = someString[Symbol.iterator](); +<pre class="brush: js">let iterator = someString[Symbol.iterator](); iterator + ""; // "[object String Iterator]" iterator.next(); // { value: "h", done: false } @@ -111,11 +111,11 @@ iterator.next(); // { value: undefined, done: true } <p>一些内置的语法结构——比如{{jsxref("Operators/Spread_operator", "展开语法")}}——其内部实现也使用了同样的迭代协议:</p> -<pre class="brush: js notranslate">[...someString] // ["h", "i"]</pre> +<pre class="brush: js">[...someString] // ["h", "i"]</pre> <p>我们可以通过提供自己的 <code>@@iterator</code> 方法,重新定义迭代行为:</p> -<pre class="brush: js notranslate">// 必须构造 String 对象以避免字符串字面量 auto-boxing +<pre class="brush: js">// 必须构造 String 对象以避免字符串字面量 auto-boxing var someString = new String("hi"); someString[Symbol.iterator] = function() { return { // 只返回一次元素,字符串 "bye",的迭代器对象 @@ -134,7 +134,7 @@ someString[Symbol.iterator] = function() { <p>注意重新定义的 <code>@@iterator</code> 方法是如何影响内置语法结构的行为的:</p> -<pre class="brush: js notranslate">[...someString]; // ["bye"] +<pre class="brush: js">[...someString]; // ["bye"] someString + ""; // "hi" </pre> @@ -148,7 +148,7 @@ someString + ""; // "hi" <p>我们可以实现一个自己的可迭代对象,就像这样:</p> -<pre class="brush: js notranslate">var myIterable = {}; +<pre class="brush: js">var myIterable = {}; myIterable[Symbol.iterator] = function* () { yield 1; yield 2; @@ -168,7 +168,7 @@ myIterable[Symbol.iterator] = function* () { <li>{{jsxref("WeakSet", "new WeakSet([<var>iterable</var>])")}}</li> </ul> -<pre class="notranslate">new Map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b" +<pre>new Map([[1, 'a'], [2, 'b'], [3, 'c']]).get(2); // "b" let myObj = {}; @@ -200,7 +200,7 @@ new WeakSet(function* () { <p>一些语句和表达式需要可迭代对象,比如 {{jsxref("Statements/for...of", "for...of")}} 循环、{{jsxref("Operators/Spread_syntax", "展开语法")}}、{{jsxref("Operators/yield*", "yield*")}},和{{jsxref("Operators/Destructuring_assignment", "解构赋值")}}。</p> -<pre class="brush: js notranslate">for(let value of ["a", "b", "c"]){ +<pre class="brush: js">for(let value of ["a", "b", "c"]){ console.log(value); } // "a" @@ -226,7 +226,7 @@ a // "a" <p>使用这样的可迭代对象很可能会导致如下的运行时(runtime)异常,或者不可预料的表现:</p> -<pre class="brush: js example-bad notranslate">var nonWellFormedIterable = {} +<pre class="brush: js example-bad">var nonWellFormedIterable = {} nonWellFormedIterable[Symbol.iterator] = () => 1 [...nonWellFormedIterable] // TypeError: [] is not a function </pre> @@ -235,7 +235,7 @@ nonWellFormedIterable[Symbol.iterator] = () => 1 <h3 id="简单迭代器">简单迭代器</h3> -<pre class="brush: js notranslate">function makeIterator(array) { +<pre class="brush: js">function makeIterator(array) { let nextIndex = 0; return { next: function () { @@ -258,7 +258,7 @@ console.log(it.next().done); // true <h3 id="无穷迭代器">无穷迭代器</h3> -<pre class="brush: js notranslate">function idMaker() { +<pre class="brush: js">function idMaker() { let index = 0; return { next: function() { @@ -280,7 +280,7 @@ console.log(it.next().value); // '2' <h3 id="使用生成器">使用生成器</h3> -<pre class="brush: js notranslate">function* makeSimpleGenerator(array) { +<pre class="brush: js">function* makeSimpleGenerator(array) { let nextIndex = 0; while(nextIndex < array.length) { @@ -313,7 +313,7 @@ console.log(gen.next().value); // '2' <h3 id="ES2015_类_class_中的迭代器">ES2015 类 class 中的迭代器</h3> -<pre class="brush: js notranslate">class SimpleClass { +<pre class="brush: js">class SimpleClass { constructor(data) { this.data = data } @@ -347,7 +347,7 @@ for (const val of simple) { <p>{{jsxref("Generator", "生成器")}}对象既是迭代器,也是可迭代对象:</p> -<pre class="brush: js notranslate">let aGeneratorObject = function* (){ +<pre class="brush: js">let aGeneratorObject = function* (){ yield 1; yield 2; yield 3; diff --git a/files/zh-cn/web/javascript/reference/operators/addition/index.html b/files/zh-cn/web/javascript/reference/operators/addition/index.html index c3726a9413..db323029cc 100644 --- a/files/zh-cn/web/javascript/reference/operators/addition/index.html +++ b/files/zh-cn/web/javascript/reference/operators/addition/index.html @@ -16,14 +16,14 @@ original_slug: Web/JavaScript/Reference/Operators/相加 <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>表达式:</strong> <var>x</var> + <var>y</var> +<pre class="syntaxbox"><strong>表达式:</strong> <var>x</var> + <var>y</var> </pre> <h2 id="示例">示例</h2> <h3 id="数字的相加运算">数字的相加运算</h3> -<pre class="brush: js notranslate">// Number + Number -> addition +<pre class="brush: js">// Number + Number -> addition 1 + 2 // 3 // Boolean + Number -> addition @@ -35,7 +35,7 @@ false + false // 0 <h3 id="字符串相加运算">字符串相加运算</h3> -<pre class="brush: js notranslate">// String + String -> concatenation +<pre class="brush: js">// String + String -> concatenation 'foo' + 'bar' // "foobar" // Number + String -> concatenation diff --git a/files/zh-cn/web/javascript/reference/operators/addition_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/addition_assignment/index.html index 9469f0f0b7..5732d5c473 100644 --- a/files/zh-cn/web/javascript/reference/operators/addition_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/addition_assignment/index.html @@ -17,14 +17,14 @@ translation_of: Web/JavaScript/Reference/Operators/Addition_assignment <h2 id="Syntax">Syntax</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x += y +<pre class="syntaxbox"><strong>Operator:</strong> x += y <strong>Meaning:</strong> x = x + y</pre> <h2 id="Examples">Examples</h2> <h3 id="Using_addition_assignment">Using addition assignment</h3> -<pre class="brush: js notranslate">// Assuming the following variables +<pre class="brush: js">// Assuming the following variables // foo = 'foo' // bar = 5 // baz = true diff --git a/files/zh-cn/web/javascript/reference/operators/assignment/index.html b/files/zh-cn/web/javascript/reference/operators/assignment/index.html index 8c981fe11e..b03fcf3224 100644 --- a/files/zh-cn/web/javascript/reference/operators/assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/assignment/index.html @@ -21,14 +21,14 @@ translation_of: Web/JavaScript/Reference/Operators/Assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x = y +<pre class="syntaxbox"><strong>Operator:</strong> x = y </pre> <h2 id="示例">示例</h2> <h3 id="简单赋值和链式赋值">简单赋值和链式赋值</h3> -<pre class="brush: js notranslate">// 假设已经存在以下变量 +<pre class="brush: js">// 假设已经存在以下变量 // x = 5 // y = 10 // z = 25 diff --git a/files/zh-cn/web/javascript/reference/operators/await/index.html b/files/zh-cn/web/javascript/reference/operators/await/index.html index 0183f4d7ae..8b07b23e41 100644 --- a/files/zh-cn/web/javascript/reference/operators/await/index.html +++ b/files/zh-cn/web/javascript/reference/operators/await/index.html @@ -15,7 +15,7 @@ translation_of: Web/JavaScript/Reference/Operators/await <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">[返回值] = await 表达式;</pre> +<pre class="syntaxbox">[返回值] = await 表达式;</pre> <dl> <dt>表达式</dt> @@ -38,7 +38,7 @@ translation_of: Web/JavaScript/Reference/Operators/await <p>如果一个 Promise 被传递给一个 await 操作符,await 将等待 Promise 正常处理完成并返回其处理结果。</p> -<pre class="brush: js notranslate">function resolveAfter2Seconds(x) { +<pre class="brush: js">function resolveAfter2Seconds(x) { return new Promise(resolve => { setTimeout(() => { resolve(x); @@ -56,7 +56,7 @@ f1(); <p>如果该值不是一个 Promise,await 会把该值转换为已正常处理的Promise,然后等待其处理结果。</p> -<pre class="brush: js notranslate">async function f2() { +<pre class="brush: js">async function f2() { var y = await 20; console.log(y); // 20 } @@ -65,7 +65,7 @@ f2(); <p>如果 Promise 处理异常,则异常值被抛出。</p> -<pre class="brush: js notranslate">async function f3() { +<pre class="brush: js">async function f3() { try { var z = await Promise.reject(30); } catch (e) { diff --git a/files/zh-cn/web/javascript/reference/operators/bitwise_and/index.html b/files/zh-cn/web/javascript/reference/operators/bitwise_and/index.html index 9010ddf09b..c857ac2b41 100644 --- a/files/zh-cn/web/javascript/reference/operators/bitwise_and/index.html +++ b/files/zh-cn/web/javascript/reference/operators/bitwise_and/index.html @@ -14,14 +14,14 @@ original_slug: Web/JavaScript/Reference/Operators/按位与 <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>a</var> & <var>b</var></code> +<pre class="syntaxbox"><code><var>a</var> & <var>b</var></code> </pre> <h2 id="描述">描述</h2> <p>操作数被转换为32位整数,并由一系列位(0和1)表示。 超过32位的数字将丢弃其最高有效位。 例如,以下大于32位的整数将被转换为32位整数:</p> -<pre class="brush: js notranslate">Before: 11100110111110100000000000000110000000000001 +<pre class="brush: js">Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001</pre> <p>第一个操作数中的每个位都与第二个操作数中的相应位配对:第一位到第一位,第二位到第二位,依此类推。</p> @@ -62,7 +62,7 @@ After: 10100000000000000110000000000001</pre> </tbody> </table> -<pre class="brush: js notranslate">. 9 (base 10) = 00000000000000000000000000001001 (base 2) +<pre class="brush: js">. 9 (base 10) = 00000000000000000000000000001001 (base 2) 14 (base 10) = 00000000000000000000000000001110 (base 2) -------------------------------- 14 & 9 (base 10) = 00000000000000000000000000001000 (base 2) = 8 (base 10) @@ -74,7 +74,7 @@ After: 10100000000000000110000000000001</pre> <h3 id="使用按位与">使用按位与</h3> -<pre class="brush: js notranslate">// 5: 00000000000000000000000000000101 +<pre class="brush: js">// 5: 00000000000000000000000000000101 // 2: 00000000000000000000000000000010 5 & 2; // 0</pre> diff --git a/files/zh-cn/web/javascript/reference/operators/bitwise_and_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/bitwise_and_assignment/index.html index 5c92f0196c..05df4461d6 100644 --- a/files/zh-cn/web/javascript/reference/operators/bitwise_and_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/bitwise_and_assignment/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Operators/Bitwise_AND_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x &= y +<pre class="syntaxbox"><strong>Operator:</strong> x &= y <strong>Meaning:</strong> x = x & y </pre> @@ -27,7 +27,7 @@ translation_of: Web/JavaScript/Reference/Operators/Bitwise_AND_assignment <h3 id="按位与赋值运算">按位与赋值运算</h3> -<pre class="brush: js notranslate">let a = 5; +<pre class="brush: js">let a = 5; // 5: 00000000000000000000000000000101 // 2: 00000000000000000000000000000010 a &= 2; // 0</pre> diff --git a/files/zh-cn/web/javascript/reference/operators/bitwise_not/index.html b/files/zh-cn/web/javascript/reference/operators/bitwise_not/index.html index ff285826b0..416bb69347 100644 --- a/files/zh-cn/web/javascript/reference/operators/bitwise_not/index.html +++ b/files/zh-cn/web/javascript/reference/operators/bitwise_not/index.html @@ -19,14 +19,14 @@ translation_of: Web/JavaScript/Reference/Operators/Bitwise_NOT <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>~a</var></code> +<pre class="syntaxbox"><code><var>~a</var></code> </pre> <h2 id="描述">描述</h2> <p>操作数被转换为32位二进制表示(0和1)。超过32位的数字将丢弃其最高有效位。如下例子中,超过32位的整数转换为32位整数:</p> -<pre class="brush: js notranslate">Before: 11100110111110100000000000000110000000000001 +<pre class="brush: js">Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001</pre> <p>第一个操作数中的每个位都与第二个操作数中的相应位配对:第一位到第一位,第二位到第二位,依此类推。</p> @@ -54,7 +54,7 @@ After: 10100000000000000110000000000001</pre> </tbody> </table> -<pre class="brush: js notranslate"> 9 (base 10) = 00000000000000000000000000001001 (base 2) +<pre class="brush: js"> 9 (base 10) = 00000000000000000000000000001001 (base 2) -------------------------------- ~9 (base 10) = 11111111111111111111111111110110 (base 2) = -10 (base 10) </pre> @@ -69,7 +69,7 @@ After: 10100000000000000110000000000001</pre> <h3 id="使用按位取反">使用按位取反</h3> -<pre class="brush: js notranslate">~0; // -1 +<pre class="brush: js">~0; // -1 ~-1; // 0 ~1; // -2 </pre> diff --git a/files/zh-cn/web/javascript/reference/operators/bitwise_or/index.html b/files/zh-cn/web/javascript/reference/operators/bitwise_or/index.html index dcd9c54de0..245da8fdab 100644 --- a/files/zh-cn/web/javascript/reference/operators/bitwise_or/index.html +++ b/files/zh-cn/web/javascript/reference/operators/bitwise_or/index.html @@ -13,14 +13,14 @@ translation_of: Web/JavaScript/Reference/Operators/Bitwise_OR <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>a</var> | <var>b</var></code> +<pre class="syntaxbox"><code><var>a</var> | <var>b</var></code> </pre> <h2 id="描述">描述</h2> <p>The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer:</p> -<pre class="brush: js notranslate">Before: 11100110111110100000000000000110000000000001 +<pre class="brush: js">Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001</pre> <p>Each bit in the first operand is paired with the corresponding bit in the second operand: <em>first bit</em> to <em>first bit</em>, <em>second bit</em> to <em>second bit</em>, and so on.</p> @@ -61,7 +61,7 @@ After: 10100000000000000110000000000001</pre> </tbody> </table> -<pre class="brush: js notranslate">. 9 (base 10) = 00000000000000000000000000001001 (base 2) +<pre class="brush: js">. 9 (base 10) = 00000000000000000000000000001001 (base 2) 14 (base 10) = 00000000000000000000000000001110 (base 2) -------------------------------- 14 | 9 (base 10) = 00000000000000000000000000001111 (base 2) = 15 (base 10) @@ -73,7 +73,7 @@ After: 10100000000000000110000000000001</pre> <h3 id="Using_bitwise_OR">Using bitwise OR</h3> -<pre class="brush: js notranslate">// 9 (00000000000000000000000000001001) +<pre class="brush: js">// 9 (00000000000000000000000000001001) // 14 (00000000000000000000000000001110) 14 | 9; diff --git a/files/zh-cn/web/javascript/reference/operators/bitwise_or_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/bitwise_or_assignment/index.html index 752a80154a..fad4f94082 100644 --- a/files/zh-cn/web/javascript/reference/operators/bitwise_or_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/bitwise_or_assignment/index.html @@ -13,14 +13,14 @@ translation_of: Web/JavaScript/Reference/Operators/Bitwise_OR_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x |= y +<pre class="syntaxbox"><strong>Operator:</strong> x |= y <strong>Meaning:</strong> x = x | y</pre> <h2 id="Examples">Examples</h2> <h3 id="Using_bitwise_OR_assignment">Using bitwise OR assignment</h3> -<pre class="brush: js notranslate">let a = 5; +<pre class="brush: js">let a = 5; a |= 2; // 7 // 5: 00000000000000000000000000000101 // 2: 00000000000000000000000000000010 diff --git a/files/zh-cn/web/javascript/reference/operators/bitwise_xor/index.html b/files/zh-cn/web/javascript/reference/operators/bitwise_xor/index.html index c2fa597627..e68e1d436b 100644 --- a/files/zh-cn/web/javascript/reference/operators/bitwise_xor/index.html +++ b/files/zh-cn/web/javascript/reference/operators/bitwise_xor/index.html @@ -13,14 +13,14 @@ translation_of: Web/JavaScript/Reference/Operators/Bitwise_XOR <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>a</var> ^ <var>b</var></code> +<pre class="syntaxbox"><code><var>a</var> ^ <var>b</var></code> </pre> <h2 id="描述">描述</h2> <p>The operands are converted to 32-bit integers and expressed by a series of bits (zeroes and ones). Numbers with more than 32 bits get their most significant bits discarded. For example, the following integer with more than 32 bits will be converted to a 32 bit integer:</p> -<pre class="brush: js notranslate">Before: 11100110111110100000000000000110000000000001 +<pre class="brush: js">Before: 11100110111110100000000000000110000000000001 After: 10100000000000000110000000000001</pre> <p>Each bit in the first operand is paired with the corresponding bit in the second operand: <em>first bit</em> to <em>first bit</em>, <em>second bit</em> to <em>second bit</em>, and so on.</p> @@ -61,7 +61,7 @@ After: 10100000000000000110000000000001</pre> </tbody> </table> -<pre class="brush: js notranslate">. 9 (base 10) = 00000000000000000000000000001001 (base 2) +<pre class="brush: js">. 9 (base 10) = 00000000000000000000000000001001 (base 2) 14 (base 10) = 00000000000000000000000000001110 (base 2) -------------------------------- 14 ^ 9 (base 10) = 00000000000000000000000000000111 (base 2) = 7 (base 10) @@ -73,7 +73,7 @@ After: 10100000000000000110000000000001</pre> <h3 id="Using_bitwise_XOR">Using bitwise XOR</h3> -<pre class="brush: js notranslate">// 9 (00000000000000000000000000001001) +<pre class="brush: js">// 9 (00000000000000000000000000001001) // 14 (00000000000000000000000000001110) 14 ^ 9; diff --git a/files/zh-cn/web/javascript/reference/operators/bitwise_xor_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/bitwise_xor_assignment/index.html index 7257e9cdb5..d8601d9eba 100644 --- a/files/zh-cn/web/javascript/reference/operators/bitwise_xor_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/bitwise_xor_assignment/index.html @@ -15,14 +15,14 @@ translation_of: Web/JavaScript/Reference/Operators/Bitwise_XOR_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x ^= y +<pre class="syntaxbox"><strong>Operator:</strong> x ^= y <strong>Meaning:</strong> x = x ^ y</pre> <h2 id="例子">例子</h2> <h3 id="使用按位异或赋值">使用按位异或赋值</h3> -<pre class="brush: js notranslate">let a = 5; // 00000000000000000000000000000101 +<pre class="brush: js">let a = 5; // 00000000000000000000000000000101 a ^= 3; // 00000000000000000000000000000011 console.log(a); // 00000000000000000000000000000110 diff --git a/files/zh-cn/web/javascript/reference/operators/decrement/index.html b/files/zh-cn/web/javascript/reference/operators/decrement/index.html index aca67c15f9..8103a647d1 100644 --- a/files/zh-cn/web/javascript/reference/operators/decrement/index.html +++ b/files/zh-cn/web/javascript/reference/operators/decrement/index.html @@ -22,7 +22,7 @@ original_slug: Web/JavaScript/Reference/Operators/自减 <h2 id="语法"><br> 语法</h2> -<pre class="syntaxbox notranslate"><strong>操作符:</strong> <var>x</var>-- or --<var>x</var> +<pre class="syntaxbox"><strong>操作符:</strong> <var>x</var>-- or --<var>x</var> </pre> <h2 id="语法细节">语法细节</h2> @@ -35,7 +35,7 @@ original_slug: Web/JavaScript/Reference/Operators/自减 <h3 id="后缀式">后缀式</h3> -<pre class="brush: js notranslate">let x = 3; +<pre class="brush: js">let x = 3; y = x--; // y = 3 @@ -44,7 +44,7 @@ y = x--; <h3 id="前缀式">前缀式</h3> -<pre class="brush: js notranslate">let a = 2; +<pre class="brush: js">let a = 2; b = --a; // a = 1 diff --git a/files/zh-cn/web/javascript/reference/operators/delete/index.html b/files/zh-cn/web/javascript/reference/operators/delete/index.html index f460f0e268..ce9d2120a4 100644 --- a/files/zh-cn/web/javascript/reference/operators/delete/index.html +++ b/files/zh-cn/web/javascript/reference/operators/delete/index.html @@ -20,12 +20,12 @@ translation_of: Web/JavaScript/Reference/Operators/delete <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate">delete <em>expression</em> +<pre class="syntaxbox">delete <em>expression</em> </pre> <p> <em>expression</em> 的计算结果应该是某个属性的引用,例如:</p> -<pre class="syntaxbox notranslate">delete <em>object.property</em> +<pre class="syntaxbox">delete <em>object.property</em> delete <em>object</em>['<em>property</em>'] </pre> @@ -72,7 +72,7 @@ delete <em>object</em>['<em>property</em>'] <p>下面的代码块给出了一个简单的例子:</p> -<pre class="brush: js notranslate">var Employee = { +<pre class="brush: js">var Employee = { age: 28, name: 'abc', designation: 'developer' @@ -89,14 +89,14 @@ console.log(delete Employee.salary); // returns true</pre> <p>当一个属性被设置为不可设置,delete操作将不会有任何效果,并且会返回false。在严格模式下会抛出语法错误({{jsxref("SyntaxError")}})。</p> -<pre class="brush: js notranslate">var Employee = {}; +<pre class="brush: js">var Employee = {}; Object.defineProperty(Employee, 'name', {configurable: false}); console.log(delete Employee.name); // returns false</pre> <p>{{jsxref("Statements/var","var")}}, {{jsxref("Statements/let","let")}}以及{{jsxref("Statements/const","const")}}创建的不可设置的属性不能被delete操作删除。</p> -<pre class="brush: js notranslate">var nameOther = 'XYZ'; +<pre class="brush: js">var nameOther = 'XYZ'; // 通过以下方法获取全局属性: Object.getOwnPropertyDescriptor(window, 'nameOther'); @@ -116,7 +116,7 @@ delete nameOther; // return false</pre> <p>在严格模式下,如果对一个变量的直接引用、函数的参数或者函数名使用delete操作,将会抛出语法错误({{jsxref("SyntaxError")}})。因此,为避免严格模式下的语法错误,必须以<code>delete object.property</code>或<code>delete object['property']</code>的形式使用delete运算符。</p> -<pre class="brush: js notranslate">Object.defineProperty(globalThis, 'variable1', { value: 10, configurable: true, }); +<pre class="brush: js">Object.defineProperty(globalThis, 'variable1', { value: 10, configurable: true, }); Object.defineProperty(globalThis, 'variable2', { value: 10, configurable: false, }); console.log(delete variable1); // true @@ -125,7 +125,7 @@ console.log(delete variable1); // true console.log(delete variable2); // false </pre> -<pre class="brush: js notranslate">function func(param) { +<pre class="brush: js">function func(param) { // SyntaxError in strict mode. console.log(delete param); // false } @@ -140,7 +140,7 @@ console.log(delete func); // false <p>任何使用var声明的变量都会被标记为不可设置的。在下面的例子中,salary是不可设置的以及不能被删除的。在非严格模式下,下面的delete操作将会返回false。</p> -<pre class="brush: js notranslate">function Employee() { +<pre class="brush: js">function Employee() { delete salary; var salary; } @@ -149,7 +149,7 @@ Employee();</pre> <p>让我们来看看相同的代码在严格模式下会有怎样的表现。会抛出一个语法错误( <code>SyntaxError)而不是返回false。</code></p> -<pre class="brush: js notranslate">"use strict"; +<pre class="brush: js">"use strict"; function Employee() { delete salary; // SyntaxError @@ -167,7 +167,7 @@ delete DemoFunction; // SyntaxError</pre> <h2 id="示例">示例</h2> -<pre class="brush: js notranslate">// 在全局作用域创建 adminName 属性 +<pre class="brush: js">// 在全局作用域创建 adminName 属性 adminName = 'xyz'; // 在全局作用域创建 empCount 属性 @@ -213,7 +213,7 @@ function f() { <p>在下面的示例中,我们删除一个对象的自己的属性,而原型链上具有相同名称的属性可用:</p> -<pre class="brush: js notranslate">function Foo() { +<pre class="brush: js">function Foo() { this.bar = 10; } @@ -240,7 +240,7 @@ console.log(foo.bar); //undefined <p>当用 <code>delete</code> 操作符删除一个数组元素时,被删除的元素已经不再属于该数组。下面的例子中用 <code>delete </code>删除了<code> trees[3]</code>。</p> -<pre class="brush: js notranslate">var trees = ["redwood","bay","cedar","oak","maple"]; +<pre class="brush: js">var trees = ["redwood","bay","cedar","oak","maple"]; delete trees[3]; if (3 in trees) { // 这里不会执行 @@ -249,7 +249,7 @@ if (3 in trees) { <p>如果你想让一个数组元素继续存在但是其值是 <code>undefined</code>,那么可以使用将 <code>undefined</code> 赋值给这个元素而不是使用 <code>delete</code>。下面的例子中,trees[3] 被赋值为 <code>undefined</code>,但该元素仍然存在。</p> -<pre class="brush: js notranslate">var trees = ["redwood","bay","cedar","oak","maple"]; +<pre class="brush: js">var trees = ["redwood","bay","cedar","oak","maple"]; trees[3] = undefined; if (3 in trees) { // 这里会被执行 @@ -257,7 +257,7 @@ if (3 in trees) { <p>如果你想通过改变数组的内容来移除一个数组元素,请使用{{jsxref("Array.splice()", "splice()")}} 方法。在下面的例子中,通过使用{{jsxref("Array.splice()", "splice()")}},将trees[3]从数组中移除。</p> -<pre class="brush: js notranslate">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; +<pre class="brush: js">var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple']; trees.splice(3,1); console.log(trees); // ["redwood", "bay", "cedar", "maple"] </pre> diff --git a/files/zh-cn/web/javascript/reference/operators/division/index.html b/files/zh-cn/web/javascript/reference/operators/division/index.html index 8bfc53db1f..d1af1e83a0 100644 --- a/files/zh-cn/web/javascript/reference/operators/division/index.html +++ b/files/zh-cn/web/javascript/reference/operators/division/index.html @@ -20,14 +20,14 @@ translation_of: Web/JavaScript/Reference/Operators/Division <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var> / <var>y</var> +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var> / <var>y</var> </pre> <h2 id="例子">例子</h2> <h3 id="基本除法">基本除法</h3> -<pre class="brush: js notranslate">1 / 2 // 0.5 +<pre class="brush: js">1 / 2 // 0.5 Math.floor(3 / 2) // 1 @@ -36,7 +36,7 @@ Math.floor(3 / 2) // 1 <h3 id="除以0">除以0</h3> -<pre class="brush: js notranslate">2.0 / 0 // Infinity +<pre class="brush: js">2.0 / 0 // Infinity 2.0 / 0.0 // Infinity, because 0.0 === 0 diff --git a/files/zh-cn/web/javascript/reference/operators/division_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/division_assignment/index.html index a5afd52f49..a9d3508d00 100644 --- a/files/zh-cn/web/javascript/reference/operators/division_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/division_assignment/index.html @@ -13,14 +13,14 @@ translation_of: Web/JavaScript/Reference/Operators/Division_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x /= y +<pre class="syntaxbox"><strong>Operator:</strong> x /= y <strong>Meaning:</strong> x = x / y</pre> <h2 id="Examples">Examples</h2> <h3 id="Using_division_assignment">Using division assignment</h3> -<pre class="brush: js notranslate">// Assuming the following variable +<pre class="brush: js">// Assuming the following variable // bar = 5 bar /= 2 // 2.5 diff --git a/files/zh-cn/web/javascript/reference/operators/equality/index.html b/files/zh-cn/web/javascript/reference/operators/equality/index.html index fadd413b17..5ea543e057 100644 --- a/files/zh-cn/web/javascript/reference/operators/equality/index.html +++ b/files/zh-cn/web/javascript/reference/operators/equality/index.html @@ -15,7 +15,7 @@ original_slug: Web/JavaScript/Reference/Operators/相等 <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">x == y +<pre class="syntaxbox">x == y </pre> <h2 id="描述">描述</h2> @@ -52,12 +52,12 @@ original_slug: Web/JavaScript/Reference/Operators/相等 <h3 id="没有类型转换的比较">没有类型转换的比较</h3> -<pre class="brush: js notranslate">1 == 1; // true +<pre class="brush: js">1 == 1; // true "hello" == "hello"; // true</pre> <h3 id="与类型转换比较">与类型转换比较</h3> -<pre class="brush: js notranslate">"1" == 1; // true +<pre class="brush: js">"1" == 1; // true 1 == "1"; // true 0 == false; // true 0 == null; // false @@ -71,7 +71,7 @@ number1 == number2; // false</pre> <h3 id="对象比较">对象比较</h3> -<pre class="brush: js notranslate">const object1 = {"key": "value"} +<pre class="brush: js">const object1 = {"key": "value"} const object2 = {"key": "value"}; object1 == object2 // false @@ -81,7 +81,7 @@ object2 == object2 // true</pre> <p>请注意,使用构造的字符串<code>new String()</code>是对象。如果将其中之一与字符串文字进行比较,则该<code>String</code>对象将被转换为字符串文字并对其内容进行比较。但是,如果两个操作数都是<code>String</code>对象,则将它们作为对象进行比较,并且必须引用相同的对象才能进行比较:</p> -<pre class="brush: js notranslate">const string1 = "hello"; +<pre class="brush: js">const string1 = "hello"; const string2 = String("hello"); const string3 = new String("hello"); const string4 = new String("hello"); @@ -94,7 +94,7 @@ console.log(string4 == string4); // true</pre> <h3 id="比较日期和字符串">比较日期和字符串</h3> -<pre class="brush: js notranslate">const d = new Date('December 17, 1995 03:24:00'); +<pre class="brush: js">const d = new Date('December 17, 1995 03:24:00'); const s = d.toString(); // for example: "Sun Dec 17 1995 03:24:00 GMT-0800 (Pacific Standard Time)" console.log(d == s); //true</pre> diff --git a/files/zh-cn/web/javascript/reference/operators/exponentiation/index.html b/files/zh-cn/web/javascript/reference/operators/exponentiation/index.html index 26fbf9ff64..7e138abfa2 100644 --- a/files/zh-cn/web/javascript/reference/operators/exponentiation/index.html +++ b/files/zh-cn/web/javascript/reference/operators/exponentiation/index.html @@ -18,7 +18,7 @@ translation_of: Web/JavaScript/Reference/Operators/Exponentiation <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>var1</var> ** <var>var2</var> +<pre class="syntaxbox"><strong>Operator:</strong> <var>var1</var> ** <var>var2</var> </pre> <h2 id="简介">简介</h2> @@ -29,7 +29,7 @@ translation_of: Web/JavaScript/Reference/Operators/Exponentiation <p>在JavaScript里,你不可能写出一个不明确的求幂表达式。这就是说,你不能立刻将一个一元运算符(<code>+/-/~/!/delete/void/typeof</code>)放在基数前,这样做只会导致一个语法错误。</p> -<pre class="brush: js notranslate">-2 ** 2; +<pre class="brush: js">-2 ** 2; // 4 in Bash, -4 in other languages. // This is invalid in JavaScript, as the operation is ambiguous. @@ -44,7 +44,7 @@ translation_of: Web/JavaScript/Reference/Operators/Exponentiation <h3 id="基本求幂">基本求幂</h3> -<pre class="brush: js notranslate">2 ** 3 // 8 +<pre class="brush: js">2 ** 3 // 8 3 ** 2 // 9 3 ** 2.5 // 15.588457268119896 10 ** -1 // 0.1 @@ -53,7 +53,7 @@ NaN ** 2 // NaN <h3 id="结合">结合</h3> -<pre class="brush: js notranslate">2 ** 3 ** 2 // 512 +<pre class="brush: js">2 ** 3 ** 2 // 512 2 ** (3 ** 2) // 512 (2 ** 3) ** 2 // 64</pre> @@ -61,12 +61,12 @@ NaN ** 2 // NaN <p>取求幂表达式的值的相反数:</p> -<pre class="brush: js notranslate">-(2 ** 2) // -4 +<pre class="brush: js">-(2 ** 2) // -4 </pre> <p>将求幂表达式的底数转化为一个负数:</p> -<pre class="brush: js notranslate">(-2) ** 2 // 4 +<pre class="brush: js">(-2) ** 2 // 4 </pre> <h2 id="规范">规范</h2> diff --git a/files/zh-cn/web/javascript/reference/operators/exponentiation_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/exponentiation_assignment/index.html index f9f53ca532..bd8e58da23 100644 --- a/files/zh-cn/web/javascript/reference/operators/exponentiation_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/exponentiation_assignment/index.html @@ -15,14 +15,14 @@ translation_of: Web/JavaScript/Reference/Operators/Exponentiation_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x **= y +<pre class="syntaxbox"><strong>Operator:</strong> x **= y <strong>Meaning:</strong> x = x ** y</pre> <h2 id="Examples">Examples</h2> <h3 id="Using_exponentiation_assignment">Using exponentiation assignment</h3> -<pre class="brush: js notranslate">// Assuming the following variable +<pre class="brush: js">// Assuming the following variable // bar = 5 bar **= 2 // 25 diff --git a/files/zh-cn/web/javascript/reference/operators/greater_than/index.html b/files/zh-cn/web/javascript/reference/operators/greater_than/index.html index afb4a2d134..0c8c8a8328 100644 --- a/files/zh-cn/web/javascript/reference/operators/greater_than/index.html +++ b/files/zh-cn/web/javascript/reference/operators/greater_than/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Greater_than <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">x > y</pre> +<pre class="syntaxbox">x > y</pre> <h2 id="描述">描述</h2> @@ -23,13 +23,13 @@ translation_of: Web/JavaScript/Reference/Operators/Greater_than <h3 id="字符串的比较">字符串的比较</h3> -<pre class="brush: js notranslate">console.log("a" > "b"); // false +<pre class="brush: js">console.log("a" > "b"); // false console.log("a" > "a"); // false console.log("a" > "3"); // true</pre> <h3 id="字符串和数字的比较">字符串和数字的比较</h3> -<pre class="brush: js notranslate">console.log("5" > 3); // true +<pre class="brush: js">console.log("5" > 3); // true console.log("3" > 3); // false console.log("3" > 5); // false @@ -41,18 +41,18 @@ console.log("3" > 5n); // false</pre> <h3 id="数字间的比较">数字间的比较</h3> -<pre class="brush: js notranslate">console.log(5 > 3); // true +<pre class="brush: js">console.log(5 > 3); // true console.log(3 > 3); // false console.log(3 > 5); // false</pre> <h3 id="数字和_BigInt_数据的比较">数字和 BigInt 数据的比较</h3> -<pre class="brush: js notranslate">console.log(5n > 3); // true +<pre class="brush: js">console.log(5n > 3); // true console.log(3 > 5n); // false</pre> <h3 id="Boolean_null_undefined_NaN的比较">Boolean, null, undefined, NaN的比较</h3> -<pre class="brush: js notranslate">console.log(true > false); // true +<pre class="brush: js">console.log(true > false); // true console.log(false > true); // false console.log(true > 0); // true diff --git a/files/zh-cn/web/javascript/reference/operators/greater_than_or_equal/index.html b/files/zh-cn/web/javascript/reference/operators/greater_than_or_equal/index.html index 9fa5b48436..f54a1061fa 100644 --- a/files/zh-cn/web/javascript/reference/operators/greater_than_or_equal/index.html +++ b/files/zh-cn/web/javascript/reference/operators/greater_than_or_equal/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Greater_than_or_equal <h2 id="Syntax">Syntax</h2> -<pre class="syntaxbox notranslate"> x >= y</pre> +<pre class="syntaxbox"> x >= y</pre> <h2 id="Description">Description</h2> @@ -23,14 +23,14 @@ translation_of: Web/JavaScript/Reference/Operators/Greater_than_or_equal <h3 id="String_to_string_comparison">String to string comparison</h3> -<pre class="brush: js notranslate">console.log("a" >= "b"); // false +<pre class="brush: js">console.log("a" >= "b"); // false console.log("a" >= "a"); // true console.log("a" >= "3"); // true </pre> <h3 id="String_to_number_comparison">String to number comparison</h3> -<pre class="brush: js notranslate">console.log("5" >= 3); // true +<pre class="brush: js">console.log("5" >= 3); // true console.log("3" >= 3); // true console.log("3" >= 5); // false @@ -39,19 +39,19 @@ console.log(5 >= "hello"); // false</pre> <h3 id="Number_to_Number_comparison">Number to Number comparison</h3> -<pre class="brush: js notranslate">console.log(5 >= 3); // true +<pre class="brush: js">console.log(5 >= 3); // true console.log(3 >= 3); // true console.log(3 >= 5); // false</pre> <h3 id="Number_to_BigInt_comparison">Number to BigInt comparison</h3> -<pre class="brush: js notranslate">console.log(5n >= 3); // true +<pre class="brush: js">console.log(5n >= 3); // true console.log(3 >= 3n); // true console.log(3 >= 5n); // false</pre> <h3 id="Comparing_Boolean_null_undefined_NaN">Comparing Boolean, null, undefined, NaN</h3> -<pre class="brush: js notranslate">console.log(true >= false); // true +<pre class="brush: js">console.log(true >= false); // true console.log(true >= true); // true console.log(false >= true); // false diff --git a/files/zh-cn/web/javascript/reference/operators/in/index.html b/files/zh-cn/web/javascript/reference/operators/in/index.html index 2ac7bb0ed4..f974698598 100644 --- a/files/zh-cn/web/javascript/reference/operators/in/index.html +++ b/files/zh-cn/web/javascript/reference/operators/in/index.html @@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Reference/Operators/in <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate"><em>prop</em> in <em>object</em></pre> +<pre class="syntaxbox"><em>prop</em> in <em>object</em></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -35,7 +35,7 @@ translation_of: Web/JavaScript/Reference/Operators/in <p>下面的例子演示了一些 <code>in</code> 运算符的用法。</p> -<pre class="brush:js notranslate">// 数组 +<pre class="brush:js">// 数组 var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); 0 in trees // 返回true 3 in trees // 返回true @@ -58,7 +58,7 @@ var mycar = {make: "Honda", model: "Accord", year: 1998}; <p><code>in</code>右操作数必须是一个对象值。例如,你可以指定使用<code>String</code>构造函数创建的字符串,但不能指定字符串文字。</p> -<pre class="brush:js notranslate">var color1 = new String("green"); +<pre class="brush:js">var color1 = new String("green"); "length" in color1 // 返回true var color2 = "coral"; "length" in color2 // 报错(color2不是对象) @@ -68,7 +68,7 @@ var color2 = "coral"; <p>如果你使用 <code><a href="/zh-CN/docs/JavaScript/Reference/Operators/delete" title="zh-CN/docs/JavaScript/Reference/Operators/Special/delete">delete</a></code> 运算符删除了一个属性,则 <code>in</code> 运算符对所删除属性返回 <code>false</code>。</p> -<pre class="brush:js notranslate">var mycar = {make: "Honda", model: "Accord", year: 1998}; +<pre class="brush:js">var mycar = {make: "Honda", model: "Accord", year: 1998}; delete mycar.make; "make" in mycar; // 返回false @@ -79,12 +79,12 @@ delete trees[3]; <p>如果你只是将一个属性的值赋值为{{jsxref("Global_Objects/undefined", "undefined")}},而没有删除它,则 <code>in</code> 运算仍然会返回<code>true</code>。</p> -<pre class="brush:js notranslate">var mycar = {make: "Honda", model: "Accord", year: 1998}; +<pre class="brush:js">var mycar = {make: "Honda", model: "Accord", year: 1998}; mycar.make = undefined; "make" in mycar; // 返回true </pre> -<pre class="brush:js notranslate">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); +<pre class="brush:js">var trees = new Array("redwood", "bay", "cedar", "oak", "maple"); trees[3] = undefined; 3 in trees; // 返回true </pre> @@ -93,7 +93,7 @@ trees[3] = undefined; <p>如果一个属性是从原型链上继承来的,<code>in</code> 运算符也会返回 <code>true</code>。</p> -<pre class="brush:js notranslate">"toString" in {}; // 返回true +<pre class="brush:js">"toString" in {}; // 返回true </pre> <h2 id="规范" style="margin-bottom: 20px; line-height: 30px;">规范</h2> diff --git a/files/zh-cn/web/javascript/reference/operators/increment/index.html b/files/zh-cn/web/javascript/reference/operators/increment/index.html index afe307f389..31620cb751 100644 --- a/files/zh-cn/web/javascript/reference/operators/increment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/increment/index.html @@ -17,7 +17,7 @@ translation_of: Web/JavaScript/Reference/Operators/Increment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var>++ or ++<var>x</var> +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var>++ or ++<var>x</var> </pre> <h2 id="描述">描述</h2> @@ -30,7 +30,7 @@ translation_of: Web/JavaScript/Reference/Operators/Increment <h3 id="后置自增Postfix_increment">后置自增(Postfix increment)</h3> -<pre class="brush: js notranslate">let x = 3; +<pre class="brush: js">let x = 3; y = x++; // y = 3 @@ -39,7 +39,7 @@ y = x++; <h3 id="前置自增Prefix_increment">前置自增(Prefix increment)</h3> -<pre class="brush: js notranslate">let a = 2; +<pre class="brush: js">let a = 2; b = ++a; // a = 3 diff --git a/files/zh-cn/web/javascript/reference/operators/inequality/index.html b/files/zh-cn/web/javascript/reference/operators/inequality/index.html index 11b16d1c2e..cbc90433e7 100644 --- a/files/zh-cn/web/javascript/reference/operators/inequality/index.html +++ b/files/zh-cn/web/javascript/reference/operators/inequality/index.html @@ -18,13 +18,13 @@ translation_of: Web/JavaScript/Reference/Operators/Inequality <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">x != y</pre> +<pre class="syntaxbox">x != y</pre> <h2 id="描述">描述</h2> <p>不等式运算符检查其操作数是否不相等。这是<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Equality">等于</a>运算符的取反,因此以下两行将始终给出相同的结果: </p> -<pre class="brush: js notranslate">x != y +<pre class="brush: js">x != y !(x == y)</pre> @@ -32,17 +32,17 @@ translation_of: Web/JavaScript/Reference/Operators/Inequality <p>与等于运算符一样,不等于运算符将尝试转换和比较不同类型的操作数:</p> -<pre class="brush: js notranslate">3 != "3"; // false</pre> +<pre class="brush: js">3 != "3"; // false</pre> <p>为避免这种情况,并要求将不同类型视为不同,请使用<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Strict_inequality">严格的不等于</a>运算符:</p> -<pre class="brush: js notranslate">3 !== "3"; // true</pre> +<pre class="brush: js">3 !== "3"; // true</pre> <h2 id="例子">例子</h2> <h3 id="没有类型转换的比较">没有类型转换的比较</h3> -<pre class="brush: js notranslate">1 != 2; // true +<pre class="brush: js">1 != 2; // true "hello" != "hola"; // true 1 != 1; // false @@ -50,7 +50,7 @@ translation_of: Web/JavaScript/Reference/Operators/Inequality <h3 id="与类型转换比较">与类型转换比较</h3> -<pre class="brush: js notranslate">"1" != 1; // false +<pre class="brush: js">"1" != 1; // false 1 != "1"; // false 0 != false; // false 0 != null; // true @@ -66,7 +66,7 @@ number1 != number2; // true</pre> <h3 id="对象比较">对象比较</h3> -<pre class="brush: js notranslate">const object1 = {"key": "value"} +<pre class="brush: js">const object1 = {"key": "value"} const object2 = {"key": "value"}; object1 != object2 // true diff --git a/files/zh-cn/web/javascript/reference/operators/instanceof/index.html b/files/zh-cn/web/javascript/reference/operators/instanceof/index.html index a1e3c5a538..9bc5622462 100644 --- a/files/zh-cn/web/javascript/reference/operators/instanceof/index.html +++ b/files/zh-cn/web/javascript/reference/operators/instanceof/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Operators/instanceof <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="notranslate"><code><em>object</em> instanceof <em>constructor</em></code></pre> +<pre><code><em>object</em> instanceof <em>constructor</em></code></pre> <h3 id="Parameters" name="Parameters">参数</h3> @@ -38,7 +38,7 @@ translation_of: Web/JavaScript/Reference/Operators/instanceof <p><code>instanceof</code> 运算符用来检测 <code>constructor.prototype </code>是否存在于参数 <code>object</code> 的原型链上。</p> -<pre class="brush: js notranslate">// 定义构造函数 +<pre class="brush: js">// 定义构造函数 function C(){} function D(){} @@ -87,7 +87,7 @@ o3 instanceof C; // true 因为 C.prototype 现在在 o3 的原型链上 <p>但是,使用对象文字符号创建的对象在这里是一个例外:虽然原型未定义,但 <code>instanceof Object</code> 返回 <code>true</code>。</p> -<pre class="brush: js notranslate">var simpleStr = "This is a simple string"; +<pre class="brush: js">var simpleStr = "This is a simple string"; var myString = new String(); var newStr = new String("String created with constructor"); var myDate = new Date(); @@ -113,7 +113,7 @@ myDate instanceof String; // 返回 false</pre> <p>下面的代码创建了一个类型 <code>Car</code>,以及该类型的对象实例 <code>mycar</code>. <code>instanceof</code> 运算符表明了这个 <code>mycar</code> 对象既属于 <code>Car</code> 类型,又属于 <code>Object</code> 类型。</p> -<pre class="brush: js notranslate">function Car(make, model, year) { +<pre class="brush: js">function Car(make, model, year) { this.make = make; this.model = model; this.year = year; @@ -128,13 +128,13 @@ var b = mycar instanceof Object; // 返回 true <p>要检测对象不是某个构造函数的实例时,你可以这样做</p> -<pre class="brush: js notranslate">if (!(mycar instanceof Car)) { +<pre class="brush: js">if (!(mycar instanceof Car)) { // Do something, like mycar = new Car(mycar) }</pre> <p>这和以下代码完全不同</p> -<pre class="brush: js notranslate">if (!mycar instanceof Car)</pre> +<pre class="brush: js">if (!mycar instanceof Car)</pre> <p>这段代码永远会得到 <code>false</code>(<code>!mycar</code> 将在 <code>instanceof</code> 之前被处理,所以你总是在验证一个布尔值是否是 <code>Car</code> 的一个实例)。</p> diff --git a/files/zh-cn/web/javascript/reference/operators/left_shift/index.html b/files/zh-cn/web/javascript/reference/operators/left_shift/index.html index 83fe088941..4bae0bcde0 100644 --- a/files/zh-cn/web/javascript/reference/operators/left_shift/index.html +++ b/files/zh-cn/web/javascript/reference/operators/left_shift/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Left_shift <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>a</var> << <var>b</var></code> +<pre class="syntaxbox"><code><var>a</var> << <var>b</var></code> </pre> <h2 id="描述">描述</h2> @@ -22,7 +22,7 @@ translation_of: Web/JavaScript/Reference/Operators/Left_shift <p>例如, <code>9 << 2</code> 得出 36:</p> -<pre class="brush: js notranslate">. 9 (十进制): 00000000000000000000000000001001 (二进制) +<pre class="brush: js">. 9 (十进制): 00000000000000000000000000001001 (二进制) -------------------------------- 9 << 2 (十进制): 00000000000000000000000000100100 (二进制) = 36 (十进制) </pre> @@ -34,7 +34,7 @@ translation_of: Web/JavaScript/Reference/Operators/Left_shift <h3 id="使用左移">使用左移</h3> -<pre class="brush: js notranslate">9 << 3; // 72 +<pre class="brush: js">9 << 3; // 72 // 9 * 2³ = 9 * 8 = 72 </pre> diff --git a/files/zh-cn/web/javascript/reference/operators/left_shift_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/left_shift_assignment/index.html index ccf5bbce00..e48b9616d0 100644 --- a/files/zh-cn/web/javascript/reference/operators/left_shift_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/left_shift_assignment/index.html @@ -15,14 +15,14 @@ translation_of: Web/JavaScript/Reference/Operators/Left_shift_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x <<= y +<pre class="syntaxbox"><strong>Operator:</strong> x <<= y <strong>Meaning:</strong> x = x << y</pre> <h2 id="Examples">Examples</h2> <h3 id="Using_left_shift_assignment">Using left shift assignment</h3> -<pre class="brush: js notranslate">let a = 5; +<pre class="brush: js">let a = 5; // 00000000000000000000000000000101 a <<= 2; // 20 diff --git a/files/zh-cn/web/javascript/reference/operators/less_than/index.html b/files/zh-cn/web/javascript/reference/operators/less_than/index.html index 1a33554b98..d98a89f03c 100644 --- a/files/zh-cn/web/javascript/reference/operators/less_than/index.html +++ b/files/zh-cn/web/javascript/reference/operators/less_than/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Less_than <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"> x < y</pre> +<pre class="syntaxbox"> x < y</pre> <h2 id="Description">Description</h2> @@ -38,13 +38,13 @@ translation_of: Web/JavaScript/Reference/Operators/Less_than <h3 id="String_to_string_comparison">String to string comparison</h3> -<pre class="brush: js notranslate">console.log("a" < "b"); // true +<pre class="brush: js">console.log("a" < "b"); // true console.log("a" < "a"); // false console.log("a" < "3"); // false</pre> <h3 id="String_to_number_comparison">String to number comparison</h3> -<pre class="brush: js notranslate">console.log("5" < 3); // false +<pre class="brush: js">console.log("5" < 3); // false console.log("3" < 3); // false console.log("3" < 5); // true @@ -56,18 +56,18 @@ console.log("3" < 5n); // true</pre> <h3 id="Number_to_Number_comparison">Number to Number comparison</h3> -<pre class="brush: js notranslate">console.log(5 < 3); // false +<pre class="brush: js">console.log(5 < 3); // false console.log(3 < 3); // false console.log(3 < 5); // true</pre> <h3 id="Number_to_BigInt_comparison">Number to BigInt comparison</h3> -<pre class="brush: js notranslate">console.log(5n < 3); // false +<pre class="brush: js">console.log(5n < 3); // false console.log(3 < 5n); // true</pre> <h3 id="Comparing_Boolean_null_undefined_NaN">Comparing Boolean, null, undefined, NaN</h3> -<pre class="brush: js notranslate">console.log(true < false); // false +<pre class="brush: js">console.log(true < false); // false console.log(false < true); // true console.log(0 < true); // true diff --git a/files/zh-cn/web/javascript/reference/operators/less_than_or_equal/index.html b/files/zh-cn/web/javascript/reference/operators/less_than_or_equal/index.html index 97a6f6746b..498dc2bbfd 100644 --- a/files/zh-cn/web/javascript/reference/operators/less_than_or_equal/index.html +++ b/files/zh-cn/web/javascript/reference/operators/less_than_or_equal/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Less_than_or_equal <h2 id="Syntax">Syntax</h2> -<pre class="syntaxbox notranslate"> x <= y</pre> +<pre class="syntaxbox"> x <= y</pre> <h2 id="Description">Description</h2> @@ -23,14 +23,14 @@ translation_of: Web/JavaScript/Reference/Operators/Less_than_or_equal <h3 id="String_to_string_comparison">String to string comparison</h3> -<pre class="brush: js notranslate">console.log("a" <= "b"); // true +<pre class="brush: js">console.log("a" <= "b"); // true console.log("a" <= "a"); // true console.log("a" <= "3"); // false </pre> <h3 id="String_to_number_comparison">String to number comparison</h3> -<pre class="brush: js notranslate">console.log("5" <= 3); // false +<pre class="brush: js">console.log("5" <= 3); // false console.log("3" <= 3); // true console.log("3" <= 5); // true @@ -39,19 +39,19 @@ console.log(5 <= "hello"); // false</pre> <h3 id="Number_to_Number_comparison">Number to Number comparison</h3> -<pre class="brush: js notranslate">console.log(5 <= 3); // false +<pre class="brush: js">console.log(5 <= 3); // false console.log(3 <= 3); // true console.log(3 <= 5); // true</pre> <h3 id="Number_to_BigInt_comparison">Number to BigInt comparison</h3> -<pre class="brush: js notranslate">console.log(5n <= 3); // false +<pre class="brush: js">console.log(5n <= 3); // false console.log(3 <= 3n); // true console.log(3 <= 5n); // true</pre> <h3 id="Comparing_Boolean_null_undefined_NaN">Comparing Boolean, null, undefined, NaN</h3> -<pre class="brush: js notranslate">console.log(true <= false); // false +<pre class="brush: js">console.log(true <= false); // false console.log(true <= true); // true console.log(false <= true); // true diff --git a/files/zh-cn/web/javascript/reference/operators/logical_and/index.html b/files/zh-cn/web/javascript/reference/operators/logical_and/index.html index 78c4eee070..e418a76518 100644 --- a/files/zh-cn/web/javascript/reference/operators/logical_and/index.html +++ b/files/zh-cn/web/javascript/reference/operators/logical_and/index.html @@ -14,7 +14,7 @@ original_slug: Web/JavaScript/Reference/Operators/逻辑和 <h2 id="Syntax">Syntax</h2> -<pre class="syntaxbox notranslate"><em>expr1</em> && <em>expr2</em> +<pre class="syntaxbox"><em>expr1</em> && <em>expr2</em> </pre> <h2 id="Description">Description</h2> @@ -43,7 +43,7 @@ original_slug: Web/JavaScript/Reference/Operators/逻辑和 <p>Short circuit means that the <code><em>expr</em></code> part above is <strong>not evaluated</strong>, hence any side effects of doing so do not take effect (e.g., if <code><em>expr</em></code> is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. See example:</p> -<pre class="brush: js notranslate">function A(){ console.log('called A'); return false; } +<pre class="brush: js">function A(){ console.log('called A'); return false; } function B(){ console.log('called B'); return true; } console.log( A() && B() ); @@ -55,7 +55,7 @@ console.log( A() && B() ); <p>The following expressions might seem equivalent, but they are not, because the <code>&&</code> operator is executed before the <code>||</code> operator (see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a>).</p> -<pre class="brush: js notranslate">true || false && false // returns true, because && is executed first +<pre class="brush: js">true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply</pre> <h2 id="Examples">Examples</h2> @@ -64,7 +64,7 @@ console.log( A() && B() ); <p>The following code shows examples of the <code>&&</code> (logical AND) operator.</p> -<pre class="brush: js notranslate">a1 = true && true // t && t returns true +<pre class="brush: js">a1 = true && true // t && t returns true a2 = true && false // t && f returns false a3 = false && true // f && t returns false a4 = false && (3 == 4) // f && f returns false @@ -80,21 +80,21 @@ a9 = false && '' // f && f returns false</pre> <p>The following operation involving <strong>booleans</strong>:</p> -<pre class="brush: js notranslate">bCondition1 && bCondition2</pre> +<pre class="brush: js">bCondition1 && bCondition2</pre> <p>is always equal to:</p> -<pre class="brush: js notranslate">!(!bCondition1 || !bCondition2)</pre> +<pre class="brush: js">!(!bCondition1 || !bCondition2)</pre> <h4 id="Converting_OR_to_AND">Converting OR to AND</h4> <p>The following operation involving <strong>booleans</strong>:</p> -<pre class="brush: js notranslate">bCondition1 || bCondition2</pre> +<pre class="brush: js">bCondition1 || bCondition2</pre> <p>is always equal to:</p> -<pre class="brush: js notranslate">!(!bCondition1 && !bCondition2)</pre> +<pre class="brush: js">!(!bCondition1 && !bCondition2)</pre> <h3 id="Removing_nested_parentheses">Removing nested parentheses</h3> @@ -102,11 +102,11 @@ a9 = false && '' // f && f returns false</pre> <p>The following composite operation involving <strong>booleans</strong>:</p> -<pre class="brush: js notranslate">bCondition1 || (bCondition2 && bCondition3)</pre> +<pre class="brush: js">bCondition1 || (bCondition2 && bCondition3)</pre> <p>is always equal to:</p> -<pre class="brush: js notranslate">bCondition1 || bCondition2 && bCondition3</pre> +<pre class="brush: js">bCondition1 || bCondition2 && bCondition3</pre> <h2 id="Specifications">Specifications</h2> diff --git a/files/zh-cn/web/javascript/reference/operators/logical_and_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/logical_and_assignment/index.html index 3ed9a1582a..4ee00585a5 100644 --- a/files/zh-cn/web/javascript/reference/operators/logical_and_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/logical_and_assignment/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Logical_AND_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><em>expr1</em> &&= <em>expr2</em> +<pre class="syntaxbox"><em>expr1</em> &&= <em>expr2</em> </pre> <h2 id="描述">描述</h2> @@ -28,18 +28,18 @@ translation_of: Web/JavaScript/Reference/Operators/Logical_AND_assignment <p>Logical AND assignment short-circuits as well meaning that <code>x &&= y</code> is equivalent to:</p> -<pre class="brush: js notranslate">x && (x = y);</pre> +<pre class="brush: js">x && (x = y);</pre> <p>And not equivalent to the following which would always perform an assignment:</p> -<pre class="brush: js notranslate example-bad">x = x && y; +<pre class="brush: js example-bad">x = x && y; </pre> <h2 id="例子">例子</h2> <h3 id="Using_logical_AND_assignment">Using logical AND assignment</h3> -<pre class="brush: js notranslate">let x = 0; +<pre class="brush: js">let x = 0; let y = 1; x &&= 0; // 0 diff --git a/files/zh-cn/web/javascript/reference/operators/logical_not/index.html b/files/zh-cn/web/javascript/reference/operators/logical_not/index.html index f05bfb180a..e27ad4db4f 100644 --- a/files/zh-cn/web/javascript/reference/operators/logical_not/index.html +++ b/files/zh-cn/web/javascript/reference/operators/logical_not/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Logical_NOT <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">!<var>expr</var> +<pre class="syntaxbox">!<var>expr</var> </pre> <h2 id="Description">Description</h2> @@ -40,7 +40,7 @@ translation_of: Web/JavaScript/Reference/Operators/Logical_NOT <p>The following code shows examples of the <code>!</code> (logical NOT) operator.</p> -<pre class="brush: js notranslate">n1 = !true // !t returns false +<pre class="brush: js">n1 = !true // !t returns false n2 = !false // !f returns true n3 = !'' // !f returns true n4 = !'Cat' // !t returns false</pre> @@ -51,7 +51,7 @@ n4 = !'Cat' // !t returns false</pre> <p>The same conversion can be done through the {{jsxref("Global_Objects/Boolean/Boolean", "Boolean")}} function.</p> -<pre class="brush: js notranslate">n1 = !!true // !!truthy returns true +<pre class="brush: js">n1 = !!true // !!truthy returns true n2 = !!{} // !!truthy returns true: <strong>any</strong> object is truthy... n3 = !!(new Boolean(false)) // ...even Boolean objects with a false <em>.valueOf()</em>! n4 = !!false // !!falsy returns false @@ -62,11 +62,11 @@ n6 = !!Boolean(false) // !!falsy returns false</pre> <p>The following operation involving <strong>booleans</strong>:</p> -<pre class="brush: js notranslate">!!bCondition</pre> +<pre class="brush: js">!!bCondition</pre> <p>is always equal to:</p> -<pre class="brush: js notranslate">bCondition</pre> +<pre class="brush: js">bCondition</pre> <h2 id="Specifications">Specifications</h2> diff --git a/files/zh-cn/web/javascript/reference/operators/logical_nullish_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/logical_nullish_assignment/index.html index a57c18e5c2..c4fea43591 100644 --- a/files/zh-cn/web/javascript/reference/operators/logical_nullish_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/logical_nullish_assignment/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Logical_nullish_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><em>expr1</em> ??= <em>expr2</em> +<pre class="syntaxbox"><em>expr1</em> ??= <em>expr2</em> </pre> <h2 id="描述">描述</h2> @@ -28,18 +28,18 @@ translation_of: Web/JavaScript/Reference/Operators/Logical_nullish_assignment <p>逻辑空赋值的语法短路也意味着 <code>x ??= y</code> 等价于:</p> -<pre class="brush: js notranslate">x ?? (x = y);</pre> +<pre class="brush: js">x ?? (x = y);</pre> <p>而不等价于如下的表达式,因为其一定会发生赋值:</p> -<pre class="brush: js notranslate example-bad">x = x ?? y; +<pre class="brush: js example-bad">x = x ?? y; </pre> <h2 id="例子">例子</h2> <h3 id="使用逻辑空赋值">使用逻辑空赋值</h3> -<pre class="brush: js notranslate">function config(options) { +<pre class="brush: js">function config(options) { options.duration ??= 100; options.speed ??= 25; return options; diff --git a/files/zh-cn/web/javascript/reference/operators/logical_or/index.html b/files/zh-cn/web/javascript/reference/operators/logical_or/index.html index 1a8f881377..3604b99140 100644 --- a/files/zh-cn/web/javascript/reference/operators/logical_or/index.html +++ b/files/zh-cn/web/javascript/reference/operators/logical_or/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Logical_OR <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><em>expr1</em> || <em>expr2</em> +<pre class="syntaxbox"><em>expr1</em> || <em>expr2</em> </pre> <h2 id="Description">Description</h2> @@ -42,7 +42,7 @@ translation_of: Web/JavaScript/Reference/Operators/Logical_OR <p>Short circuit means that the <code><em>expr</em></code> part above is <strong>not evaluated</strong>, hence any side effects of doing so do not take effect (e.g., if <code><em>expr</em></code> is a function call, the calling never takes place). This happens because the value of the operator is already determined after the evaluation of the first operand. See example:</p> -<pre class="brush: js notranslate">function A(){ console.log('called A'); return false; } +<pre class="brush: js">function A(){ console.log('called A'); return false; } function B(){ console.log('called B'); return true; } console.log( B() || A() ); @@ -54,7 +54,7 @@ console.log( B() || A() ); <p>The following expressions might seem equivalent, but they are not, because the <code>&&</code> operator is executed before the <code>||</code> operator (see <a href="/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence">operator precedence</a>).</p> -<pre class="brush: js notranslate">true || false && false // returns true, because && is executed first +<pre class="brush: js">true || false && false // returns true, because && is executed first (true || false) && false // returns false, because operator precedence cannot apply</pre> <h2 id="Examples">Examples</h2> @@ -63,7 +63,7 @@ console.log( B() || A() ); <p>The following code shows examples of the <code>||</code> (logical OR) operator.</p> -<pre class="brush: js notranslate">o1 = true || true // t || t returns true +<pre class="brush: js">o1 = true || true // t || t returns true o2 = false || true // f || t returns true o3 = true || false // t || f returns true o4 = false || (3 == 4) // f || f returns false @@ -85,21 +85,21 @@ o10 = false || varObject // f || object returns varObject <p>The following operation involving <strong>booleans</strong>:</p> -<pre class="brush: js notranslate">bCondition1 && bCondition2</pre> +<pre class="brush: js">bCondition1 && bCondition2</pre> <p>is always equal to:</p> -<pre class="brush: js notranslate">!(!bCondition1 || !bCondition2)</pre> +<pre class="brush: js">!(!bCondition1 || !bCondition2)</pre> <h4 id="Converting_OR_to_AND">Converting OR to AND</h4> <p>The following operation involving <strong>booleans</strong>:</p> -<pre class="brush: js notranslate">bCondition1 || bCondition2</pre> +<pre class="brush: js">bCondition1 || bCondition2</pre> <p>is always equal to:</p> -<pre class="brush: js notranslate">!(!bCondition1 && !bCondition2)</pre> +<pre class="brush: js">!(!bCondition1 && !bCondition2)</pre> <h3 id="Removing_nested_parentheses">Removing nested parentheses</h3> @@ -107,11 +107,11 @@ o10 = false || varObject // f || object returns varObject <p>The following composite operation involving <strong>booleans</strong>:</p> -<pre class="brush: js notranslate">bCondition1 && (bCondition2 || bCondition3)</pre> +<pre class="brush: js">bCondition1 && (bCondition2 || bCondition3)</pre> <p>is always equal to:</p> -<pre class="brush: js notranslate">!(!bCondition1 || !bCondition2 && !bCondition3)</pre> +<pre class="brush: js">!(!bCondition1 || !bCondition2 && !bCondition3)</pre> <h2 id="Specifications">Specifications</h2> diff --git a/files/zh-cn/web/javascript/reference/operators/multiplication/index.html b/files/zh-cn/web/javascript/reference/operators/multiplication/index.html index db346f4cbe..a37d1e7a54 100644 --- a/files/zh-cn/web/javascript/reference/operators/multiplication/index.html +++ b/files/zh-cn/web/javascript/reference/operators/multiplication/index.html @@ -15,25 +15,25 @@ translation_of: Web/JavaScript/Reference/Operators/Multiplication <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var> * <var>y</var> +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var> * <var>y</var> </pre> <h2 id="例子">例子</h2> <h3 id="使用数字相乘">使用数字相乘</h3> -<pre class="brush: js notranslate"> 2 * 2 // 4 +<pre class="brush: js"> 2 * 2 // 4 -2 * 2 // -4 </pre> <h3 id="使用_Infinity_相乘">使用 Infinity 相乘</h3> -<pre class="brush: js notranslate">Infinity * 0 // NaN +<pre class="brush: js">Infinity * 0 // NaN Infinity * Infinity // Infinity</pre> <h3 id="使用非数字相乘">使用非数字相乘</h3> -<pre class="brush: js notranslate">'foo' * 2 // NaN</pre> +<pre class="brush: js">'foo' * 2 // NaN</pre> <h2 id="规范">规范</h2> diff --git a/files/zh-cn/web/javascript/reference/operators/multiplication_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/multiplication_assignment/index.html index e05019acba..274729034b 100644 --- a/files/zh-cn/web/javascript/reference/operators/multiplication_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/multiplication_assignment/index.html @@ -15,14 +15,14 @@ translation_of: Web/JavaScript/Reference/Operators/Multiplication_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x *= y +<pre class="syntaxbox"><strong>Operator:</strong> x *= y <strong>Meaning:</strong> x = x * y</pre> <h2 id="Examples">Examples</h2> <h3 id="Using_multiplication_assignment">Using multiplication assignment</h3> -<pre class="brush: js notranslate">// Assuming the following variable +<pre class="brush: js">// Assuming the following variable // bar = 5 bar *= 2 // 10 diff --git a/files/zh-cn/web/javascript/reference/operators/new/index.html b/files/zh-cn/web/javascript/reference/operators/new/index.html index 0b2d5c24c7..e6833d4cc7 100644 --- a/files/zh-cn/web/javascript/reference/operators/new/index.html +++ b/files/zh-cn/web/javascript/reference/operators/new/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Operators/new <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">new <em>constructor</em>[([<em>arguments</em>])]</pre> +<pre class="syntaxbox">new <em>constructor</em>[([<em>arguments</em>])]</pre> <h3 id="参数">参数</h3> @@ -67,7 +67,7 @@ translation_of: Web/JavaScript/Reference/Operators/new <p>你可以使用 <code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">Function.prototype</a></code> 属性将共享属性添加到以前定义的对象类型。这定义了一个由该函数创建的所有对象共享的属性,而不仅仅是对象类型的其中一个实例。下面的代码将一个值为 <code>null</code> 的 <code>color</code> 属性添加到 <code>car</code> 类型的所有对象,然后仅在实例对象 <code>car1</code> 中用字符串 "<code>black</code>" 覆盖该值。详见 <a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/prototype">prototype</a>。</p> -<pre class="brush: js notranslate">function Car() {} +<pre class="brush: js">function Car() {} car1 = new Car(); car2 = new Car(); @@ -95,7 +95,7 @@ console.log(car2.color) // original color <p>假设你要创建一个汽车的对象类型。你希望这个类型叫做car,这个类型具备make, model, year等属性,要做到这些,你需要写这样一个函数:</p> -<pre class="brush: js notranslate">function Car(make, model, year) { +<pre class="brush: js">function Car(make, model, year) { this.make = make; this.model = model; this.year = year; @@ -104,19 +104,19 @@ console.log(car2.color) // original color <p>现在,你可以如下所示创建一个 <code>mycar</code> 的对象:</p> -<pre class="brush: js notranslate">var mycar = new Car("Eagle", "Talon TSi", 1993);</pre> +<pre class="brush: js">var mycar = new Car("Eagle", "Talon TSi", 1993);</pre> <p>这段代码创建了 <code>mycar</code> 并给他的属性指定值,于是 <code>mycar.make</code> 的值为"<code>Eagle</code>", <code>mycar.year</code> 的值为1993,以此类推。</p> <p>你可以通过调用 <code>new</code> 来创建任意个汽车对象。例如:</p> -<pre class="brush: js notranslate">var kenscar = new Car("Nissan", "300ZX", 1992);</pre> +<pre class="brush: js">var kenscar = new Car("Nissan", "300ZX", 1992);</pre> <h3 id="对象属性为其他对象">对象属性为其他对象</h3> <p>假设你定义了一个对象叫做 <code>person</code>:</p> -<pre class="brush: js notranslate">function Person(name, age, sex) { +<pre class="brush: js">function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; @@ -125,13 +125,13 @@ console.log(car2.color) // original color <p>然后实例化两个新的 <code>person</code> 对象如下:</p> -<pre class="brush: js notranslate">var rand = new Person("Rand McNally", 33, "M"); +<pre class="brush: js">var rand = new Person("Rand McNally", 33, "M"); var ken = new Person("Ken Jones", 39, "M"); </pre> <p>然后你可以重写 <code>car</code> 的定义,添加一个值为 <code>person</code> 对象的 <code>owner</code> 属性,如下:</p> -<pre class="brush: js notranslate">function Car(make, model, year, owner) { +<pre class="brush: js">function Car(make, model, year, owner) { this.make = make; this.model = model; this.year = year; @@ -141,13 +141,13 @@ var ken = new Person("Ken Jones", 39, "M"); <p>为了实例化新的对象,你可以用如下代码:</p> -<pre class="brush: js notranslate">var car1 = new Car("Eagle", "Talon TSi", 1993, rand); +<pre class="brush: js">var car1 = new Car("Eagle", "Talon TSi", 1993, rand); var car2 = new Car("Nissan", "300ZX", 1992, ken); </pre> <p>创建对象时,并没有传字符串或数字给owner,而是传了对象 <code>rand</code> 和 <code>ken</code> 。这个时候,你可以这样来获取 <code>car2</code> 的owner的name:</p> -<pre class="brush: js notranslate">car2.owner.name</pre> +<pre class="brush: js">car2.owner.name</pre> <h2 id="规范">规范</h2> diff --git a/files/zh-cn/web/javascript/reference/operators/nullish_coalescing_operator/index.html b/files/zh-cn/web/javascript/reference/operators/nullish_coalescing_operator/index.html index 59b7443e60..1dfd0302a9 100644 --- a/files/zh-cn/web/javascript/reference/operators/nullish_coalescing_operator/index.html +++ b/files/zh-cn/web/javascript/reference/operators/nullish_coalescing_operator/index.html @@ -23,7 +23,7 @@ translation_of: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>leftExpr</var> ?? <var>rightExpr</var> +<pre class="syntaxbox"><var>leftExpr</var> ?? <var>rightExpr</var> </pre> <h2 id="示例">示例</h2> @@ -32,7 +32,7 @@ translation_of: Web/JavaScript/Reference/Operators/Nullish_coalescing_operator <p>在这个例子中,我们使用空值合并操作符为常量提供默认值,保证常量不为 <code>null</code> 或者 <code>undefined</code>。</p> -<pre class="brush: js notranslate">const nullValue = null; +<pre class="brush: js">const nullValue = null; const emptyText = ""; // 空字符串,是一个假值,Boolean("") === false const someNumber = 42; @@ -48,14 +48,14 @@ console.log(valC); // 42</pre> <p>以前,如果想为一个变量赋默认值,通常的做法是使用逻辑或操作符(<code><a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Logical_OR">||</a></code>):</p> -<pre class="brush: js notranslate">let foo; +<pre class="brush: js">let foo; // foo is never assigned any value so it is still undefined let someDummyText = foo || 'Hello!';</pre> <p>然而,由于 <code>||</code> 是一个布尔逻辑运算符,左侧的操作数会被强制转换成布尔值用于求值。任何假值(<code>0</code>, <code>''</code>, <code>NaN</code>, <code>null</code>, <code>undefined</code>)都不会被返回。这导致如果你使用<code>0</code>,<code>''</code>或<code>NaN</code>作为有效值,就会出现不可预料的后果。</p> -<pre class="brush: js notranslate">let count = 0; +<pre class="brush: js">let count = 0; let text = ""; let qty = count || 42; @@ -65,7 +65,7 @@ console.log(message); // "hi!",而不是 ""</pre> <p>空值合并操作符可以避免这种陷阱,其只在第一个操作数为<code>null</code> 或 <code>undefined</code> 时(而不是其它假值)返回第二个操作数:</p> -<pre class="brush: js notranslate">let myText = ''; // An empty string (which is also a falsy value) +<pre class="brush: js">let myText = ''; // An empty string (which is also a falsy value) let notFalsyText = myText || 'Hello world'; console.log(notFalsyText); // Hello world @@ -78,7 +78,7 @@ console.log(preservingFalsy); // '' (as myText is neither undefined nor null) <p>与 OR 和 AND 逻辑操作符相似,当左表达式不为 <code>null</code> 或 <code>undefined</code> 时,不会对右表达式进行求值。</p> -<pre class="brush: js notranslate">function A() { console.log('函数 A 被调用了'); return undefined; } +<pre class="brush: js">function A() { console.log('函数 A 被调用了'); return undefined; } function B() { console.log('函数 B 被调用了'); return false; } function C() { console.log('函数 C 被调用了'); return "foo"; } @@ -96,19 +96,19 @@ console.log( B() ?? C() ); <p>将 <code>??</code> 直接与 AND(<code>&&</code>)和 OR(<code>||</code>)操作符组合使用是不可取的。(译者注:应当是因为空值合并操作符和其他逻辑操作符之间的运算优先级/运算顺序是未定义的)这种情况下会抛出 <code><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code> 。</p> -<pre class="brush: js example-bad notranslate">null || undefined ?? "foo"; // 抛出 SyntaxError +<pre class="brush: js example-bad">null || undefined ?? "foo"; // 抛出 SyntaxError true || undefined ?? "foo"; // 抛出 SyntaxError</pre> <p>但是,如果使用括号来显式表明运算优先级,是没有问题的:</p> -<pre class="brush: js example-good notranslate">(null || undefined ) ?? "foo"; // 返回 "foo" +<pre class="brush: js example-good">(null || undefined ) ?? "foo"; // 返回 "foo" </pre> <h3 id="与可选链式操作符(.)的关系">与可选链式操作符(<code>?.</code>)的关系</h3> <p>空值合并操作符针对 <code>undefined</code> 与 <code>null</code> 这两个值,<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Optional_chaining">可选链式操作符(<code>?.</code>)</a> 也是如此。在这访问属性可能为 <code>undefined</code> 与 <code>null</code> 的对象时,可选链式操作符非常有用。</p> -<pre class="brush: js notranslate">let foo = { someFooProp: "hi" }; +<pre class="brush: js">let foo = { someFooProp: "hi" }; console.log(foo.someFooProp?.toUpperCase()); // "HI" console.log(foo.someBarProp?.toUpperCase()); // undefined diff --git a/files/zh-cn/web/javascript/reference/operators/optional_chaining/index.html b/files/zh-cn/web/javascript/reference/operators/optional_chaining/index.html index 6f639f537a..e765e6d66b 100644 --- a/files/zh-cn/web/javascript/reference/operators/optional_chaining/index.html +++ b/files/zh-cn/web/javascript/reference/operators/optional_chaining/index.html @@ -26,7 +26,7 @@ original_slug: Web/JavaScript/Reference/Operators/可选链 <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><var>obj</var>?.<var>prop</var> +<pre class="syntaxbox"><var>obj</var>?.<var>prop</var> <var>obj</var>?.[<var>expr</var>] <var>arr</var>?.[<var>index</var>] <var>func</var>?.(<var>args</var>) @@ -38,19 +38,19 @@ original_slug: Web/JavaScript/Reference/Operators/可选链 <p>比如,思考一个存在嵌套结构的对象 <code>obj</code>。不使用可选链的话,查找一个深度嵌套的子属性时,需要验证之间的引用,例如:</p> -<pre class="brush: js notranslate">let nestedProp = obj.first && obj.first.second;</pre> +<pre class="brush: js">let nestedProp = obj.first && obj.first.second;</pre> <p>为了避免报错,在访问<code>obj.first.second</code>之前,要保证 <code>obj.first</code> 的值既不是 <code>null</code>,也不是 <code>undefined</code>。如果只是直接访问 <code>obj.first.second</code>,而不对 <code>obj.first</code> 进行校验,则有可能抛出错误。</p> <p>有了可选链操作符(<code>?.</code>),在访问 <code>obj.first.second</code> 之前,不再需要明确地校验 <code>obj.first</code> 的状态,再并用短路计算获取最终结果:</p> -<pre class="brush: js notranslate">let nestedProp = obj.first?.second;</pre> +<pre class="brush: js">let nestedProp = obj.first?.second;</pre> <p>通过使用 <code>?.</code> 操作符取代 <code>.</code> 操作符,JavaScript 会在尝试访问 <code>obj.first.second</code> 之前,先隐式地检查并确定 <code>obj.first</code> 既不是 <code>null</code> 也不是 <code>undefined</code>。如果<code>obj.first </code>是 <code>null</code> 或者 <code>undefined</code>,表达式将会短路计算直接返回 <code>undefined</code>。</p> <p>这等价于以下表达式,但实际上没有创建临时变量:</p> -<pre class="brush: js notranslate">let temp = obj.first; +<pre class="brush: js">let temp = obj.first; let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second);</pre> <h3 id="可选链与函数调用">可选链与函数调用</h3> @@ -59,7 +59,7 @@ let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.secon <p>函数调用时如果被调用的方法不存在,使用可选链可以使表达式自动返回<code>undefined</code>而不是抛出一个异常。</p> -<pre class="brush: js notranslate">let result = someInterface.customMethod?.();</pre> +<pre class="brush: js">let result = someInterface.customMethod?.();</pre> <div class="blockIndicator note"> <p><strong>注意:</strong> 如果存在一个属性名且不是函数, 使用 <code>?.</code> 仍然会产生一个 {{JSxRef("TypeError")}} 异常 (<code>x.y</code><code> is not a function</code>).</p> @@ -73,7 +73,7 @@ let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.secon <p>如果使用<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment">解构赋值</a>来解构的一个对象的回调函数或 fetch 方法,你可能得到不能当做函数直接调用的不存在的值,除非你已经校验了他们的存在性。使用<code>?.</code>的你可以忽略这些额外的校验:</p> -<pre class="brush: js notranslate">// ES2019的写法 +<pre class="brush: js">// ES2019的写法 function doSomething(onContent, onError) { try { // ... do something with the data @@ -86,7 +86,7 @@ function doSomething(onContent, onError) { } </pre> -<pre class="brush: js notranslate">// 使用可选链进行函数调用 +<pre class="brush: js">// 使用可选链进行函数调用 function doSomething(onContent, onError) { try { // ... do something with the data @@ -101,16 +101,16 @@ function doSomething(onContent, onError) { <p>当使用<a href="/zh-CN/docs/Web/JavaScript/Reference/Operators/Property_Accessors#方括号表示法">方括号与属性名</a>的形式来访问属性时,你也可以使用可选链操作符:</p> -<pre class="brush: js notranslate">let nestedProp = obj?.['prop' + 'Name'];</pre> +<pre class="brush: js">let nestedProp = obj?.['prop' + 'Name'];</pre> <h3 id="可选链不能用于赋值">可选链不能用于赋值</h3> -<pre class="notranslate"><code>let object = {}; +<pre><code>let object = {}; object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignment</code></pre> <h3 id="可选链访问数组元素">可选链访问数组元素</h3> -<pre class="notranslate">let arrayItem = arr?.[42];</pre> +<pre>let arrayItem = arr?.[42];</pre> <h2 id="例子">例子</h2> @@ -118,7 +118,7 @@ object?.property = 1; // Uncaught SyntaxError: Invalid left-hand side in assignm <p>如下的例子在一个不含 <code>bar</code> 成员的 Map 中查找 <code>bar</code> 成员的 <code>name</code> 属性,因此结果是 <code>undefined</code>。</p> -<pre class="brush: js notranslate">let myMap = new Map(); +<pre class="brush: js">let myMap = new Map(); myMap.set("foo", {name: "baz", desc: "inga"}); let nameBar = myMap.get("bar")?.name;</pre> @@ -127,7 +127,7 @@ let nameBar = myMap.get("bar")?.name;</pre> <p>当在表达式中使用可选链时,如果左操作数是 <code>null</code> 或 <code>undefined</code>,表达式将不会被计算,例如:</p> -<pre class="brush: js notranslate">let potentiallyNullObj = null; +<pre class="brush: js">let potentiallyNullObj = null; let x = 0; let prop = potentiallyNullObj?.[x++]; @@ -138,7 +138,7 @@ console.log(x); // x 将不会被递增,依旧输出 0 <p>可以连续使用可选链读取多层嵌套结构:</p> -<pre class="brush: js notranslate">let customer = { +<pre class="brush: js">let customer = { name: "Carl", details: { age: 82, @@ -155,7 +155,7 @@ let duration = vacations.trip?.getTime?.(); <p>{{JSxRef("Operators/Nullish_Coalescing_Operator", "空值合并操作符")}}可以在使用可选链时设置一个默认值:</p> -<pre class="brush: js notranslate"><code>let customer = { +<pre class="brush: js"><code>let customer = { name: "Carl", details: { age: 82 } }; diff --git a/files/zh-cn/web/javascript/reference/operators/remainder/index.html b/files/zh-cn/web/javascript/reference/operators/remainder/index.html index f09292e4ff..a2d1e19fa6 100644 --- a/files/zh-cn/web/javascript/reference/operators/remainder/index.html +++ b/files/zh-cn/web/javascript/reference/operators/remainder/index.html @@ -21,14 +21,14 @@ original_slug: Web/JavaScript/Reference/Operators/取余 <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>var1</var> % <var>var2</var> +<pre class="syntaxbox"><strong>Operator:</strong> <var>var1</var> % <var>var2</var> </pre> <h2 id="示例">示例</h2> <h3 id="被除数为正数">被除数为正数</h3> -<pre class="brush: js notranslate"> 12 % 5 // 2 +<pre class="brush: js"> 12 % 5 // 2 1 % -2 // 1 1 % 2 // 1 2 % 3 // 2 @@ -37,13 +37,13 @@ original_slug: Web/JavaScript/Reference/Operators/取余 <h3 id="被除数为负数">被除数为负数</h3> -<pre class="brush: js notranslate">-12 % 5 // -2 +<pre class="brush: js">-12 % 5 // -2 -1 % 2 // -1 -4 % 2 // -0</pre> <h3 id="被除数为NaN">被除数为NaN</h3> -<pre class="brush: js notranslate">NaN % 2 // NaN</pre> +<pre class="brush: js">NaN % 2 // NaN</pre> <h2 id="规范">规范</h2> diff --git a/files/zh-cn/web/javascript/reference/operators/remainder_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/remainder_assignment/index.html index a9d015e467..d36fa7cdc3 100644 --- a/files/zh-cn/web/javascript/reference/operators/remainder_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/remainder_assignment/index.html @@ -15,14 +15,14 @@ translation_of: Web/JavaScript/Reference/Operators/Remainder_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x %= y +<pre class="syntaxbox"><strong>Operator:</strong> x %= y <strong>Meaning:</strong> x = x % y</pre> <h2 id="Examples">Examples</h2> <h3 id="Using_remainder_assignment">Using remainder assignment</h3> -<pre class="brush: js notranslate">// Assuming the following variable +<pre class="brush: js">// Assuming the following variable // bar = 5 bar %= 2 // 1 diff --git a/files/zh-cn/web/javascript/reference/operators/right_shift/index.html b/files/zh-cn/web/javascript/reference/operators/right_shift/index.html index f049a499a9..583da5cafe 100644 --- a/files/zh-cn/web/javascript/reference/operators/right_shift/index.html +++ b/files/zh-cn/web/javascript/reference/operators/right_shift/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Right_shift <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>a</var> >> <var>b</var></code> +<pre class="syntaxbox"><code><var>a</var> >> <var>b</var></code> </pre> <h2 id="Description">Description</h2> @@ -22,14 +22,14 @@ translation_of: Web/JavaScript/Reference/Operators/Right_shift <p>For example, <code>9 >> 2</code> yields 2:</p> -<pre class="brush: js notranslate">. 9 (base 10): 00000000000000000000000000001001 (base 2) +<pre class="brush: js">. 9 (base 10): 00000000000000000000000000001001 (base 2) -------------------------------- 9 >> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10) </pre> <p>Likewise, <code>-9 >> 2</code> yields <code>-3</code>, because the sign is preserved:</p> -<pre class="brush: js notranslate">. -9 (base 10): 11111111111111111111111111110111 (base 2) +<pre class="brush: js">. -9 (base 10): 11111111111111111111111111110111 (base 2) -------------------------------- -9 >> 2 (base 10): 11111111111111111111111111111101 (base 2) = -3 (base 10) </pre> @@ -38,7 +38,7 @@ translation_of: Web/JavaScript/Reference/Operators/Right_shift <h3 id="Using_right_shift">Using right shift</h3> -<pre class="brush: js notranslate"> 9 >> 2; // 2 +<pre class="brush: js"> 9 >> 2; // 2 -9 >> 2; // -3 </pre> diff --git a/files/zh-cn/web/javascript/reference/operators/right_shift_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/right_shift_assignment/index.html index f9e8b3c8c4..0ebfbbd51e 100644 --- a/files/zh-cn/web/javascript/reference/operators/right_shift_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/right_shift_assignment/index.html @@ -15,14 +15,14 @@ translation_of: Web/JavaScript/Reference/Operators/Right_shift_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x >>= y +<pre class="syntaxbox"><strong>Operator:</strong> x >>= y <strong>Meaning:</strong> x = x >> y</pre> <h2 id="Examples">Examples</h2> <h3 id="Using_right_shift_assignment">Using right shift assignment</h3> -<pre class="brush: js notranslate">let a = 5; // (00000000000000000000000000000101) +<pre class="brush: js">let a = 5; // (00000000000000000000000000000101) a >>= 2; // 1 (00000000000000000000000000000001) let b = -5; // (-00000000000000000000000000000101) diff --git a/files/zh-cn/web/javascript/reference/operators/spread_syntax/index.html b/files/zh-cn/web/javascript/reference/operators/spread_syntax/index.html index 0397ee8e96..3f21c5b960 100644 --- a/files/zh-cn/web/javascript/reference/operators/spread_syntax/index.html +++ b/files/zh-cn/web/javascript/reference/operators/spread_syntax/index.html @@ -20,15 +20,15 @@ translation_of: Web/JavaScript/Reference/Operators/Spread_syntax <p>函数调用:</p> -<pre class="syntaxbox notranslate">myFunction(...iterableObj);</pre> +<pre class="syntaxbox">myFunction(...iterableObj);</pre> <p>字面量数组构造或字符串:</p> -<pre class="notranslate">[...iterableObj, '4', ...'hello', 6];</pre> +<pre>[...iterableObj, '4', ...'hello', 6];</pre> <p>构造字面量对象时,进行克隆或者属性拷贝(ECMAScript 2018规范新增特性):</p> -<pre class="syntaxbox notranslate">let objClone = { ...obj };</pre> +<pre class="syntaxbox">let objClone = { ...obj };</pre> <h2 id="示例">示例</h2> @@ -38,19 +38,19 @@ translation_of: Web/JavaScript/Reference/Operators/Spread_syntax <p>如果想将数组元素迭代为函数参数,一般使用{{jsxref( "Function.prototype.apply")}} 的方式进行调用。</p> -<pre class="brush: js notranslate">function myFunction(x, y, z) { } +<pre class="brush: js">function myFunction(x, y, z) { } var args = [0, 1, 2]; myFunction.apply(null, args);</pre> <p>有了展开语法,可以这样写:</p> -<pre class="brush: js notranslate"><code>function myFunction(x, y, z) { } +<pre class="brush: js"><code>function myFunction(x, y, z) { } var args = [0, 1, 2]; myFunction(...args);</code></pre> <p>所有参数都可以通过展开语法来传值,也不限制多次使用展开语法。</p> -<pre class="brush: js notranslate">function myFunction(v, w, x, y, z) { } +<pre class="brush: js">function myFunction(v, w, x, y, z) { } var args = [0, 1]; myFunction(-1, ...args, 2, ...[3]);</pre> @@ -58,13 +58,13 @@ myFunction(-1, ...args, 2, ...[3]);</pre> <p>使用 <code>new</code> 关键字来调用构造函数时,不能<strong>直接</strong>使用数组+ <code>apply</code> 的方式(<code>apply</code> 执行的是调用 <code>[[Call]]</code> , 而不是构造 <code>[[Construct]]</code>)。当然, 有了展开语法, 将数组展开为构造函数的参数就很简单了:</p> -<pre class="brush: js notranslate">var dateFields = [1970, 0, 1]; // 1970年1月1日 +<pre class="brush: js">var dateFields = [1970, 0, 1]; // 1970年1月1日 var d = new Date(...dateFields);</font></font> </pre> <p>如果不使用展开语法, 想将数组元素传给构造函数, 实现方式可能是这样的:</p> -<pre class="brush: js notranslate">function applyAndNew(constructor, args) { +<pre class="brush: js">function applyAndNew(constructor, args) { function partial () { return constructor.apply(this, args); }; @@ -96,7 +96,7 @@ console.log(new myConstructorWithArguments); <p>没有展开语法的时候,只能组合使用 <code>push</code>, <code>splice</code>, <code>concat</code> 等方法,来将已有数组元素变成新数组的一部分。有了展开语法, 通过字面量方式, 构造新数组会变得更简单、更优雅:</p> -<pre class="brush: js notranslate">var parts = ['shoulders', 'knees']; +<pre class="brush: js">var parts = ['shoulders', 'knees']; var lyrics = ['head', ...parts, 'and', 'toes']; </font></font> // ["head", "shoulders", "knees", "and", "toes"] </pre> @@ -105,7 +105,7 @@ var lyrics = ['head', ...parts, 'and', 'toes']; </font></font> <h4 id="数组拷贝copy">数组拷贝(copy)</h4> -<pre class="brush: js notranslate">var arr = [1, 2, 3]; +<pre class="brush: js">var arr = [1, 2, 3]; var arr2 = [...arr]; // like arr.slice() arr2.push(4); @@ -115,7 +115,7 @@ arr2.push(4); <p><strong>提示:</strong> 实际上, 展开语法和 {{jsxref("Object.assign()")}} 行为一致, 执行的都是浅拷贝(只遍历一层)。如果想对多维数组进行深拷贝, 下面的示例就有些问题了。</p> -<pre class="brush: js notranslate">var a = [[1], [2], [3]]; +<pre class="brush: js">var a = [[1], [2], [3]]; var b = [...a]; b.shift().shift(); // 1 // Now array a is affected as well: [[2], [3]] @@ -125,28 +125,28 @@ b.shift().shift(); // 1 <p>{{jsxref("Array.concat")}} 函数常用于将一个数组连接到另一个数组的后面。如果不使用展开语法, 代码可能是下面这样的:</p> -<pre class="brush: js notranslate">var arr1 = [0, 1, 2]; +<pre class="brush: js">var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; // 将 arr2 中所有元素附加到 arr1 后面并返回 var arr3 = arr1.concat(arr2);</pre> <p>使用展开语法:</p> -<pre class="brush: js notranslate">var arr1 = [0, 1, 2]; +<pre class="brush: js">var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; var arr3 = [...arr1, ...arr2]; </pre> <p>{{jsxref("Array.unshift")}} 方法常用于在数组的开头插入新元素/数组. 不使用展开语法, 示例如下:</p> -<pre class="brush: js notranslate">var arr1 = [0, 1, 2]; +<pre class="brush: js">var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; // 将 arr2 中的元素插入到 arr1 的开头 Array.prototype.unshift.apply(arr1, arr2) // arr1 现在是 [3, 4, 5, 0, 1, 2]</pre> <p>如果使用展开语法, 代码如下: [请注意, 这里使用展开语法创建了一个新的 <code>arr1</code> 数组, {{jsxref("Array.unshift")}} 方法则是修改了原本存在的 <code>arr1</code> 数组]:</p> -<pre class="brush: js notranslate">var arr1 = [0, 1, 2]; +<pre class="brush: js">var arr1 = [0, 1, 2]; var arr2 = [3, 4, 5]; arr1 = [...arr2, ...arr1]; // arr1 现在为 [3, 4, 5, 0, 1, 2] </pre> @@ -157,7 +157,7 @@ arr1 = [...arr2, ...arr1]; // arr1 现在为 [3, 4, 5, 0, 1, 2] <p>浅拷贝(Shallow-cloning, 不包含 prototype) 和对象合并, 可以使用更简短的展开语法。而不必再使用 {{jsxref("Object.assign()")}} 方式.</p> -<pre class="brush: js notranslate">var obj1 = { foo: 'bar', x: 42 }; +<pre class="brush: js">var obj1 = { foo: 'bar', x: 42 }; var obj2 = { foo: 'baz', y: 13 }; var clonedObj = { ...obj1 }; @@ -173,7 +173,7 @@ var mergedObj = { ...obj1, ...obj2 }; <p><strong>提示</strong>: 不能替换或者模拟 {{jsxref("Object.assign()")}} 函数:</p> -<pre class="notranslate"><code>var obj1 = { foo: 'bar', x: 42 }; +<pre><code>var obj1 = { foo: 'bar', x: 42 }; var obj2 = { foo: 'baz', y: 13 }; const merge = ( ...objects ) => ( { ...objects } ); @@ -191,7 +191,7 @@ var mergedObj = merge ( {}, obj1, obj2); <p>在数组或函数参数中使用展开语法时, 该语法只能用于 <a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator">可迭代对象</a>:</p> -<pre class="brush: js notranslate">var obj = {'key1': 'value1'}; +<pre class="brush: js">var obj = {'key1': 'value1'}; var array = [...obj]; // TypeError: obj is not iterable </pre> diff --git a/files/zh-cn/web/javascript/reference/operators/strict_equality/index.html b/files/zh-cn/web/javascript/reference/operators/strict_equality/index.html index 125b67c168..1b8211841a 100644 --- a/files/zh-cn/web/javascript/reference/operators/strict_equality/index.html +++ b/files/zh-cn/web/javascript/reference/operators/strict_equality/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Strict_equality <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">x === y</pre> +<pre class="syntaxbox">x === y</pre> <h2 id="描述">描述</h2> @@ -39,7 +39,7 @@ translation_of: Web/JavaScript/Reference/Operators/Strict_equality <h3 id="比较相同类型的操作数">比较相同类型的操作数</h3> -<pre class="brush: js notranslate">console.log("hello" === "hello"); // true +<pre class="brush: js">console.log("hello" === "hello"); // true console.log("hello" === "hola"); // false console.log(3 === 3); // true @@ -52,7 +52,7 @@ console.log(null === null); // true</pre> <h3 id="比较不同类型的操作数">比较不同类型的操作数</h3> -<pre class="brush: js notranslate">console.log("3" === 3); // false +<pre class="brush: js">console.log("3" === 3); // false console.log(true === 1); // false @@ -60,7 +60,7 @@ console.log(null === undefined); // false</pre> <h3 id="比较对象">比较对象</h3> -<pre class="brush: js notranslate">const object1 = { +<pre class="brush: js">const object1 = { name: "hello" } diff --git a/files/zh-cn/web/javascript/reference/operators/strict_inequality/index.html b/files/zh-cn/web/javascript/reference/operators/strict_inequality/index.html index a31aa575d1..26efd1748f 100644 --- a/files/zh-cn/web/javascript/reference/operators/strict_inequality/index.html +++ b/files/zh-cn/web/javascript/reference/operators/strict_inequality/index.html @@ -13,13 +13,13 @@ translation_of: Web/JavaScript/Reference/Operators/Strict_inequality <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">x !== y</pre> +<pre class="syntaxbox">x !== y</pre> <h2 id="描述">描述</h2> <p>严格不等式运算符检查其对象是否不相等。它是严格相等运算符的否定,因此下面两行总是会给出相同的结果:</p> -<pre class="brush: js notranslate">x !== y +<pre class="brush: js">x !== y !(x === y)</pre> @@ -27,13 +27,13 @@ translation_of: Web/JavaScript/Reference/Operators/Strict_inequality <p>与严格相等运算符一样,严格不等运算符始终认为不同类型的对象是不同的:</p> -<pre class="brush: js notranslate">3 !== "3"; // true</pre> +<pre class="brush: js">3 !== "3"; // true</pre> <h2 id="示例">示例</h2> <h3 id="比较相同类型的对象">比较相同类型的对象</h3> -<pre class="brush: js notranslate">console.log("hello" !== "hello"); // false +<pre class="brush: js">console.log("hello" !== "hello"); // false console.log("hello" !== "hola"); // true console.log(3 !== 3); // false @@ -46,7 +46,7 @@ console.log(null !== null); // false</pre> <h3 id="比较不同类型的对象">比较不同类型的对象</h3> -<pre class="brush: js notranslate">console.log("3" !== 3); // true +<pre class="brush: js">console.log("3" !== 3); // true console.log(true !== 1); // true @@ -54,7 +54,7 @@ console.log(null !== undefined); // true</pre> <h3 id="比较Object对象">比较Object对象</h3> -<pre class="brush: js notranslate">const object1 = { +<pre class="brush: js">const object1 = { name: "hello" } diff --git a/files/zh-cn/web/javascript/reference/operators/subtraction/index.html b/files/zh-cn/web/javascript/reference/operators/subtraction/index.html index 00dcee2a1e..c4307e2ace 100644 --- a/files/zh-cn/web/javascript/reference/operators/subtraction/index.html +++ b/files/zh-cn/web/javascript/reference/operators/subtraction/index.html @@ -15,19 +15,19 @@ translation_of: Web/JavaScript/Reference/Operators/Subtraction <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> <var>x</var> - <var>y</var> +<pre class="syntaxbox"><strong>Operator:</strong> <var>x</var> - <var>y</var> </pre> <h2 id="Examples">Examples</h2> <h3 id="Subtraction_with_numbers">Subtraction with numbers</h3> -<pre class="brush: js notranslate">5 - 3 // 2 +<pre class="brush: js">5 - 3 // 2 3 - 5 // -2</pre> <h3 id="Subtraction_with_non-numbers">Subtraction with non-numbers</h3> -<pre class="brush: js notranslate">'foo' - 3 // NaN</pre> +<pre class="brush: js">'foo' - 3 // NaN</pre> <h2 id="Specifications">Specifications</h2> diff --git a/files/zh-cn/web/javascript/reference/operators/subtraction_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/subtraction_assignment/index.html index 93dc5a138b..9d96a67f7e 100644 --- a/files/zh-cn/web/javascript/reference/operators/subtraction_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/subtraction_assignment/index.html @@ -15,14 +15,14 @@ translation_of: Web/JavaScript/Reference/Operators/Subtraction_assignment <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x -= y +<pre class="syntaxbox"><strong>Operator:</strong> x -= y <strong>Meaning:</strong> x = x - y</pre> <h2 id="Examples">Examples</h2> <h3 id="Using_subtraction_assignment">Using subtraction assignment</h3> -<pre class="brush: js notranslate">// Assuming the following variable +<pre class="brush: js">// Assuming the following variable // bar = 5 bar -= 2 // 3 diff --git a/files/zh-cn/web/javascript/reference/operators/super/index.html b/files/zh-cn/web/javascript/reference/operators/super/index.html index 1f279cb42f..ba936e09ba 100644 --- a/files/zh-cn/web/javascript/reference/operators/super/index.html +++ b/files/zh-cn/web/javascript/reference/operators/super/index.html @@ -16,7 +16,7 @@ translation_of: Web/JavaScript/Reference/Operators/super <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">super([arguments]); +<pre class="syntaxbox">super([arguments]); // 调用 父对象/父类 的构造函数 super.functionOnParent([arguments]); @@ -33,7 +33,7 @@ super.functionOnParent([arguments]); <p>以下代码片段来自于 <a href="https://github.com/GoogleChrome/samples/blob/gh-pages/classes-es6/index.html">classes sample</a>。</p> -<pre class="brush: js notranslate">class Polygon { +<pre class="brush: js">class Polygon { constructor(height, width) { this.name = 'Rectangle'; this.height = height; @@ -69,7 +69,7 @@ class Square extends Polygon { <p>你也可以用 super 调用父类的<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/static">静态方法</a>。</p> -<pre class="brush: js notranslate">class Rectangle { +<pre class="brush: js">class Rectangle { constructor() {} static logNbSides() { return 'I have 4 sides'; @@ -88,7 +88,7 @@ Square.logDescription(); // 'I have 4 sides which are all equal'</pre> <p>你不能使用 <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete">delete 操作符</a> 加 <code>super.prop</code> 或者 <code>super[expr]</code> 去删除父类的属性,这样做会抛出 {{jsxref("ReferenceError")}}。</p> -<pre class="brush: js notranslate">class Base { +<pre class="brush: js">class Base { constructor() {} foo() {} } @@ -105,7 +105,7 @@ new Derived().delete(); // ReferenceError: invalid delete involving 'super'.</pr <p>当使用 {{jsxref("Object.defineProperty")}} 定义一个属性为不可写时,<code>super</code>将不能重写这个属性的值。</p> -<pre class="brush: js notranslate">class X { +<pre class="brush: js">class X { constructor() { Object.defineProperty(this, 'prop', { configurable: true, @@ -132,7 +132,7 @@ console.log(y.prop); // 1</pre> <p><code>Super</code>也可以在<a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer">object initializer / literal</a> 符号中使用。在下面的例子中,两个对象各定义了一个方法。在第二个对象中, 我们使用<code>super</code>调用了第一个对象中的方法。 当然,这需要我们先利用 {{jsxref("Object.setPrototypeOf()")}} 设置<code>obj2</code>的原型为<code>obj1</code>,然后才能够使用<code>super</code>调用 <code>obj1</code>上的<code>method1</code>。</p> -<pre class="brush: js notranslate">var obj1 = { +<pre class="brush: js">var obj1 = { method1() { console.log("method 1"); } diff --git a/files/zh-cn/web/javascript/reference/operators/this/index.html b/files/zh-cn/web/javascript/reference/operators/this/index.html index aea931541f..86616407d0 100644 --- a/files/zh-cn/web/javascript/reference/operators/this/index.html +++ b/files/zh-cn/web/javascript/reference/operators/this/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Operators/this <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">this</pre> +<pre class="syntaxbox">this</pre> <h3 id="值">值</h3> @@ -32,7 +32,7 @@ translation_of: Web/JavaScript/Reference/Operators/this <p>无论是否在严格模式下,在全局执行环境中(在任何函数体外部)<code>this</code> 都指向全局对象。</p> -<pre class="brush:js notranslate">// 在浏览器中, window 对象同时也是全局对象: +<pre class="brush:js">// 在浏览器中, window 对象同时也是全局对象: console.log(this === window); // true a = 37; @@ -52,7 +52,7 @@ console.log(b) // "MDN"</pre> <p>因为下面的代码不在严格模式下,且 <code>this</code> 的值不是由该调用设置的,所以 <code>this</code> 的值默认指向全局对象,浏览器中就是 {{domxref("Window", "window")}}。</p> -<pre class="brush:js notranslate">function f1(){ +<pre class="brush:js">function f1(){ return this; } //在浏览器中: @@ -64,7 +64,7 @@ f1() === globalThis; <p>然而,在严格模式下,如果进入执行环境时没有设置 <code>this</code> 的值,<code>this</code> 会保持为 <code>undefined</code>,如下:</p> -<pre class="brush:js notranslate">function f2(){ +<pre class="brush:js">function f2(){ "use strict"; // 这里是严格模式 return this; } @@ -82,7 +82,7 @@ f2() === undefined; // true <p>在类的构造函数中,<code>this</code> 是一个常规对象。类中所有非静态的方法都会被添加到 <code>this</code> 的原型中:</p> -<pre class="notranslate">class Example { +<pre>class Example { constructor() { const proto = Object.getPrototypeOf(this); console.log(Object.getOwnPropertyNames(proto)); @@ -102,7 +102,7 @@ new Example(); // ['constructor', 'first', 'second']</pre> <p>不像基类的构造函数,派生类的构造函数没有初始的 <code>this</code> 绑定。在构造函数中调用 {{jsxref("Operators/super", "super()")}} 会生成一个 <code>this</code> 绑定,并相当于执行如下代码,Base为基类:</p> -<pre class="notranslate">this = new Base();</pre> +<pre>this = new Base();</pre> <div class="blockIndicator warning"> <p><strong>警告:</strong>在调用 <code>super()</code> 之前引用 <code>this</code> 会抛出错误。</p> @@ -110,7 +110,7 @@ new Example(); // ['constructor', 'first', 'second']</pre> <p>派生类不能在调用 <code>super()</code> 之前返回,除非其构造函数返回的是一个对象,或者根本没有构造函数。</p> -<pre class="notranslate">class Base {} +<pre>class Base {} class Good extends Base {} class AlsoGood extends Base { constructor() { @@ -147,7 +147,7 @@ whatsThis.apply(obj); // 'Custom' 因为函数中的 this 被设置为obj <h3 id="this_和对象转换">this 和对象转换</h3> -<pre class="notranslate">function add(c, d) { +<pre>function add(c, d) { return this.a + this.b + c + d; } @@ -164,7 +164,7 @@ add.apply(o, [10, 20]); // 34 <p>在非严格模式下使用 <code>call</code> 和 <code>apply</code> 时,如果用作 <code>this</code> 的值不是对象,则会被尝试转换为对象。<code>null</code> 和 <code>undefined</code> 被转换为全局对象。原始值如 <code>7</code> 或 <code>'foo'</code> 会使用相应构造函数转换为对象。因此 <code>7</code> 会被转换为 <code>new Number(7)</code> 生成的对象,字符串 <code>'foo'</code> 会转换为 <code>new String('foo')</code> 生成的对象。</p> -<pre class="notranslate">function bar() { +<pre>function bar() { console.log(Object.prototype.toString.call(this)); } @@ -176,7 +176,7 @@ bar.call(undefined); // [object global]</pre> <p>ECMAScript 5 引入了 {{jsxref("Function.prototype.bind()")}}。调用<code>f.bind(someObject)</code>会创建一个与<code>f</code>具有相同函数体和作用域的函数,但是在这个新函数中,<code>this</code>将永久地被绑定到了<code>bind</code>的第一个参数,无论这个函数是如何被调用的。</p> -<pre class="brush:js notranslate">function f(){ +<pre class="brush:js">function f(){ return this.a; } @@ -194,7 +194,7 @@ console.log(o.a, o.f(), o.g(), o.h()); // 37, 37, azerty, azerty <p>在<a href="/zh-CN/docs/Web/JavaScript/Reference/Functions/Arrow_functions">箭头函数</a>中,<code>this</code>与封闭词法环境的<code>this</code>保持一致。在全局代码中,它将被设置为全局对象:</p> -<pre class="brush: js notranslate">var globalObject = this; +<pre class="brush: js">var globalObject = this; var foo = (() => this); console.log(foo() === globalObject); // true</pre> @@ -202,7 +202,7 @@ console.log(foo() === globalObject); // true</pre> <p>注意:如果将<code>this</code>传递给<code>call</code>、<code>bind</code>、或者<code>apply</code>来调用箭头函数,它将被忽略。不过你仍然可以为调用添加参数,不过第一个参数(<code>thisArg</code>)应该设置为<code>null</code>。</p> </div> -<pre class="brush: js notranslate">// 接着上面的代码 +<pre class="brush: js">// 接着上面的代码 // 作为对象的一个方法调用 var obj = {foo: foo}; console.log(obj.foo() === globalObject); // true @@ -216,7 +216,7 @@ console.log(foo() === globalObject); // true</pre> <p>无论如何,<code>foo</code> 的 <code>this</code> 被设置为他被创建时的环境(在上面的例子中,就是全局对象)。这同样适用于在其他函数内创建的箭头函数:这些箭头函数的<code>this</code>被设置为封闭的词法环境的。</p> -<pre class="brush: js notranslate">// 创建一个含有bar方法的obj对象, +<pre class="brush: js">// 创建一个含有bar方法的obj对象, // bar返回一个函数, // 这个函数返回this, // 这个返回的函数是以箭头函数创建的, @@ -252,7 +252,7 @@ console.log(fn2()() == window); // true</pre> <p>下面的例子中,当 <code>o.f()</code> 被调用时,函数内的 <code>this</code> 将绑定到 <code>o</code> 对象。</p> -<pre class="brush:js notranslate">var o = { +<pre class="brush:js">var o = { prop: 37, f: function() { return this.prop; @@ -264,7 +264,7 @@ console.log(o.f()); // 37 <p>请注意,这样的行为完全不会受函数定义方式或位置的影响。在前面的例子中,我们在定义对象<code>o</code>的同时,将其中的函数定义为成员 <code>f</code> 。但是,我们也可以先定义函数,然后再将其附属到<code>o.f</code>。这样做的结果是一样的:</p> -<pre class="brush:js notranslate">var o = {prop: 37}; +<pre class="brush:js">var o = {prop: 37}; function independent() { return this.prop; @@ -279,14 +279,14 @@ console.log(o.f()); // 37 <p>同样,<code>this</code> 的绑定只受最接近的成员引用的影响。在下面的这个例子中,我们把一个方法<code>g</code>当作对象<code>o.b</code>的函数调用。在这次执行期间,函数中的<code>this</code>将指向<code>o.b</code>。事实证明,这与他是对象 <code>o</code> 的成员没有多大关系,最近的引用才是最重要的。</p> -<pre class="brush: js notranslate"><code>o.b = {g: independent, prop: 42}; +<pre class="brush: js"><code>o.b = {g: independent, prop: 42}; console.log(o.b.g()); // 42</code></pre> <h4 id="原型链中的_this">原型链中的 <code><strong>this</strong></code></h4> <p>对于在对象原型链上某处定义的方法,同样的概念也适用。如果该方法存在于一个对象的原型链上,那么 <code>this</code> 指向的是调用这个方法的对象,就像该方法就在这个对象上一样。</p> -<pre class="brush:js notranslate">var o = { +<pre class="brush:js">var o = { f: function() { return this.a + this.b; } @@ -304,7 +304,7 @@ console.log(p.f()); // 5 <p>再次,相同的概念也适用于当函数在一个 <code>getter</code> 或者 <code>setter</code> 中被调用。用作 <code>getter</code> 或 <code>setter</code> 的函数都会把 <code>this</code> 绑定到设置或获取属性的对象。</p> -<pre class="brush: js notranslate">function sum() { +<pre class="brush: js">function sum() { return this.a + this.b + this.c; } @@ -331,7 +331,7 @@ console.log(o.average, o.sum); // logs 2, 6 <p>虽然构造函数返回的默认值是 <code>this</code> 所指的那个对象,但它仍可以手动返回其他的对象(如果返回值不是一个对象,则返回 <code>this</code> 对象)。</p> </div> -<pre class="brush: js notranslate">/* +<pre class="brush: js">/* * 构造函数这样工作: * * function MyConstructor(){ @@ -370,7 +370,7 @@ console.log(o.a); // logs 38 <p>当函数被用作事件处理函数时,它的 <code>this</code> 指向触发事件的元素(一些浏览器在使用非 <code>addEventListener</code> 的函数动态地添加监听函数时不遵守这个约定)。</p> -<pre class="brush:js notranslate">// 被调用时,将关联的元素变成蓝色 +<pre class="brush:js">// 被调用时,将关联的元素变成蓝色 function bluify(e){ console.log(this === e.currentTarget); // 总是 true @@ -391,14 +391,14 @@ for(var i=0 ; i<elements.length ; i++){ <p>当代码被内联 <a href="/zh-CN/docs/Web/Guide/Events/Event_handlers">on-event 处理函数</a> 调用时,它的<code>this</code>指向监听器所在的DOM元素:</p> -<pre class="brush: html notranslate"><button onclick="alert(this.tagName.toLowerCase());"> +<pre class="brush: html"><button onclick="alert(this.tagName.toLowerCase());"> Show this </button> </pre> <p>上面的 alert 会显示 <code>button</code>。注意只有外层代码中的 <code>this</code> 是这样设置的:</p> -<pre class="brush: html notranslate"><button onclick="alert((function(){return this})());"> +<pre class="brush: html"><button onclick="alert((function(){return this})());"> Show inner this </button> </pre> @@ -409,7 +409,7 @@ for(var i=0 ; i<elements.length ; i++){ <p>和其他普通函数一样,方法中的 <code>this</code> 值取决于它们如何被调用。有时,改写这个行为,让类中的 <code>this</code> 值总是指向这个类实例会很有用。为了做到这一点,可在构造函数中绑定类方法:</p> -<pre class="notranslate">class Car { +<pre>class Car { constructor() { // Bind sayBye but not sayHi to show the difference this.sayBye = this.sayBye.bind(this); diff --git a/files/zh-cn/web/javascript/reference/operators/typeof/index.html b/files/zh-cn/web/javascript/reference/operators/typeof/index.html index 41cf3c8da9..60cd51b992 100644 --- a/files/zh-cn/web/javascript/reference/operators/typeof/index.html +++ b/files/zh-cn/web/javascript/reference/operators/typeof/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Operators/typeof <p><code>typeof</code> 运算符后接操作数:</p> -<pre class="syntaxbox notranslate">typeof <em>operand +<pre class="syntaxbox">typeof <em>operand typeof(operand)</em> </pre> @@ -88,7 +88,7 @@ typeof(operand)</em> <h2 id="示例">示例</h2> -<pre class="brush: js notranslate">// 数值 +<pre class="brush: js">// 数值 typeof 37 === 'number'; typeof 3.14 === 'number'; typeof(42) === 'number'; @@ -152,7 +152,7 @@ typeof Math.sin === 'function'; <h3 id="typeof_null"><code>typeof null</code></h3> -<pre class="brush: js notranslate"><code>// JavaScript 诞生以来便如此 +<pre class="brush: js"><code>// JavaScript 诞生以来便如此 typeof null === 'object';</code></pre> <p>在 JavaScript 最初的实现中,JavaScript 中的值是由一个表示类型的标签和实际数据值表示的。对象的类型标签是 0。由于 <code>null</code> 代表的是空指针(大多数平台下值为 0x00),因此,null 的类型标签是 0,<code>typeof null</code> 也因此返回 <code>"object"</code>。(<a href="http://www.2ality.com/2013/10/typeof-null.html">参考来源</a>)</p> @@ -161,7 +161,7 @@ typeof null === 'object';</code></pre> <h3 id="使用_new_操作符">使用 <code>new</code> 操作符</h3> -<pre class="brush: js notranslate">// 除 Function 外的所有构造函数的类型都是 'object' +<pre class="brush: js">// 除 Function 外的所有构造函数的类型都是 'object' var str = new String('String'); var num = new Number(100); @@ -174,7 +174,7 @@ typeof func; // 返回 'function'</pre> <h3 id="语法中的括号">语法中的括号</h3> -<pre class="brush: js notranslate">// 括号有无将决定表达式的类型。 +<pre class="brush: js">// 括号有无将决定表达式的类型。 var iData = 99; typeof iData + ' Wisen'; // 'number Wisen' @@ -184,7 +184,7 @@ typeof (iData + ' Wisen'); // 'string'</pre> <p>对正则表达式字面量的类型判断在某些浏览器中不符合标准:</p> -<pre class="brush: js notranslate">typeof /s/ === 'function'; // Chrome 1-12 , 不符合 ECMAScript 5.1 +<pre class="brush: js">typeof /s/ === 'function'; // Chrome 1-12 , 不符合 ECMAScript 5.1 typeof /s/ === 'object'; // Firefox 5+ , 符合 ECMAScript 5.1 </pre> @@ -194,7 +194,7 @@ typeof /s/ === 'object'; // Firefox 5+ , 符合 ECMAScript 5.1 <p>但在加入了块级作用域的 <a href="/zh-CN/docs/Web/JavaScript/Reference/Statements/let">let</a> 和 <a href="/zh-CN/docs/Web/JavaScript/Reference/Statements/const">const</a> 之后,在其被声明之前对块中的 <code>let</code> 和 <code>const</code> 变量使用 <code>typeof</code> 会抛出一个 <a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/ReferenceError">ReferenceError</a>。块作用域变量在块的头部处于“<a href="/zh-CN/docs/Web/JavaScript/Reference/Statements/let#Temporal_Dead_Zone_and_errors_with_let">暂存死区</a>”,直至其被初始化,在这期间,访问变量将会引发错误。</p> -<pre class="brush: js notranslate">typeof undeclaredVariable === 'undefined'; +<pre class="brush: js">typeof undeclaredVariable === 'undefined'; typeof newLetVariable; // ReferenceError typeof newConstVariable; // ReferenceError @@ -208,7 +208,7 @@ class newClass{};</pre> <p>当前所有的浏览器都暴露了一个类型为 <code>undefined</code> 的非标准宿主对象 {{domxref("document.all")}}。</p> -<pre class="brush: js notranslate">typeof document.all === 'undefined'; +<pre class="brush: js">typeof document.all === 'undefined'; </pre> <p>尽管规范允许为非标准的外来对象自定义类型标签,但它要求这些类型标签与已有的不同。<code>document.all</code> 的类型标签为 <code>'undefined'</code> 的例子在 Web 领域中被归类为对原 ECMA JavaScript 标准的“故意侵犯”。</p> @@ -219,7 +219,7 @@ class newClass{};</pre> <p>For greater specificity in checking types, a <code>typeof</code> wrapper for usage in production-level code would be as follows (provided <code>obj</code> exists):</p> -<pre class="brush: js notranslate"> function type(obj, fullClass) { +<pre class="brush: js"> function type(obj, fullClass) { // get toPrototypeString() of obj (handles all types) // Early JS environments return '[object Object]' for null, so it's best to directly check for it. @@ -265,7 +265,7 @@ class newClass{};</pre> <p>在 IE 6, 7 和 8 上,很多宿主对象是对象而不是函数。例如:</p> -<pre class="brush: js notranslate">typeof alert === 'object'</pre> +<pre class="brush: js">typeof alert === 'object'</pre> </div> <div class="brush:js language-js line-number" style=""></div> diff --git a/files/zh-cn/web/javascript/reference/operators/unary_negation/index.html b/files/zh-cn/web/javascript/reference/operators/unary_negation/index.html index 2170b92c53..887a79a2a0 100644 --- a/files/zh-cn/web/javascript/reference/operators/unary_negation/index.html +++ b/files/zh-cn/web/javascript/reference/operators/unary_negation/index.html @@ -13,14 +13,14 @@ translation_of: Web/JavaScript/Reference/Operators/Unary_negation <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> -<var>x</var> +<pre class="syntaxbox"><strong>Operator:</strong> -<var>x</var> </pre> <h2 id="Examples">Examples</h2> <h3 id="Negating_numbers">Negating numbers</h3> -<pre class="brush: js notranslate">const x = 3; +<pre class="brush: js">const x = 3; const y = -x; // y = -3 @@ -31,7 +31,7 @@ const y = -x; <p>The unary negation operator can convert a non-number into a number.</p> -<pre class="brush: js notranslate">const x = "4"; +<pre class="brush: js">const x = "4"; const y = -x; // y = -4 diff --git a/files/zh-cn/web/javascript/reference/operators/unary_plus/index.html b/files/zh-cn/web/javascript/reference/operators/unary_plus/index.html index 9f3b818df9..da09fa1f02 100644 --- a/files/zh-cn/web/javascript/reference/operators/unary_plus/index.html +++ b/files/zh-cn/web/javascript/reference/operators/unary_plus/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Unary_plus <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> +<var>x</var> +<pre class="syntaxbox"><strong>Operator:</strong> +<var>x</var> </pre> <h2 id="Description">Description</h2> @@ -24,7 +24,7 @@ translation_of: Web/JavaScript/Reference/Operators/Unary_plus <h3 id="Usage_with_numbers">Usage with numbers</h3> -<pre class="brush: js notranslate">const x = 1; +<pre class="brush: js">const x = 1; const y = -1; console.log(+x); @@ -34,7 +34,7 @@ console.log(+y); <h3 id="Usage_with_non-numbers">Usage with non-numbers</h3> -<pre class="brush: js notranslate">+true // 1 +<pre class="brush: js">+true // 1 +false // 0 +null // 0 +function(val){ return val } // NaN diff --git a/files/zh-cn/web/javascript/reference/operators/unsigned_right_shift/index.html b/files/zh-cn/web/javascript/reference/operators/unsigned_right_shift/index.html index f40a28e8b0..52f18ea92c 100644 --- a/files/zh-cn/web/javascript/reference/operators/unsigned_right_shift/index.html +++ b/files/zh-cn/web/javascript/reference/operators/unsigned_right_shift/index.html @@ -13,7 +13,7 @@ translation_of: Web/JavaScript/Reference/Operators/Unsigned_right_shift <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code><var>a</var> >>> <var>b</var></code> +<pre class="syntaxbox"><code><var>a</var> >>> <var>b</var></code> </pre> <h2 id="描述">描述</h2> @@ -22,14 +22,14 @@ translation_of: Web/JavaScript/Reference/Operators/Unsigned_right_shift <p>For non-negative numbers, zero-fill right shift and sign-propagating right shift yield the same result. For example, <code>9 >>> 2</code> yields 2, the same as <code>9 >> 2</code>:</p> -<pre class="brush: js notranslate">. 9 (base 10): 00000000000000000000000000001001 (base 2) +<pre class="brush: js">. 9 (base 10): 00000000000000000000000000001001 (base 2) -------------------------------- 9 >>> 2 (base 10): 00000000000000000000000000000010 (base 2) = 2 (base 10) </pre> <p>However, this is not the case for negative numbers. For example, <code>-9 >>> 2</code> yields 1073741821, which is different than <code>-9 >> 2</code> (which yields <code>-3</code>):</p> -<pre class="brush: js notranslate">. -9 (base 10): 11111111111111111111111111110111 (base 2) +<pre class="brush: js">. -9 (base 10): 11111111111111111111111111110111 (base 2) -------------------------------- -9 >>> 2 (base 10): 00111111111111111111111111111101 (base 2) = 1073741821 (base 10) </pre> @@ -38,7 +38,7 @@ translation_of: Web/JavaScript/Reference/Operators/Unsigned_right_shift <h3 id="Using_unsigned_right_shift">Using unsigned right shift</h3> -<pre class="brush: js notranslate"> 9 >>> 2; // 2 +<pre class="brush: js"> 9 >>> 2; // 2 -9 >>> 2; // 1073741821 </pre> diff --git a/files/zh-cn/web/javascript/reference/operators/unsigned_right_shift_assignment/index.html b/files/zh-cn/web/javascript/reference/operators/unsigned_right_shift_assignment/index.html index 76379358c0..0c2e1fb3c5 100644 --- a/files/zh-cn/web/javascript/reference/operators/unsigned_right_shift_assignment/index.html +++ b/files/zh-cn/web/javascript/reference/operators/unsigned_right_shift_assignment/index.html @@ -15,14 +15,14 @@ translation_of: Web/JavaScript/Reference/Operators/Unsigned_right_shift_assignme <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><strong>Operator:</strong> x >>>= y +<pre class="syntaxbox"><strong>Operator:</strong> x >>>= y <strong>Meaning:</strong> x = x >>> y</pre> <h2 id="例子">例子</h2> <h3 id="Using_unsigned_right_shift_assignment">Using unsigned right shift assignment</h3> -<pre class="brush: js notranslate">let a = 5; // (00000000000000000000000000000101) +<pre class="brush: js">let a = 5; // (00000000000000000000000000000101) a >>>= 2; // 1 (00000000000000000000000000000001) let b = -5; // (-00000000000000000000000000000101) diff --git a/files/zh-cn/web/javascript/reference/statements/async_function/index.html b/files/zh-cn/web/javascript/reference/statements/async_function/index.html index 37aad08974..b4bdd88173 100644 --- a/files/zh-cn/web/javascript/reference/statements/async_function/index.html +++ b/files/zh-cn/web/javascript/reference/statements/async_function/index.html @@ -23,7 +23,7 @@ translation_of: Web/JavaScript/Reference/Statements/async_function <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">async function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { +<pre class="syntaxbox">async function <em>name</em>([<em>param</em>[, <em>param</em>[, ... <em>param</em>]]]) { <em> statements </em> } </pre> @@ -65,14 +65,14 @@ translation_of: Web/JavaScript/Reference/Statements/async_function <p>例如,如下代码:</p> -<pre class="syntaxbox notranslate">async function <var>foo</var>() { +<pre class="syntaxbox">async function <var>foo</var>() { <var>return 1</var> } </pre> <p>等价于:</p> -<pre class="syntaxbox notranslate">function <var>foo</var>() { +<pre class="syntaxbox">function <var>foo</var>() { <var>return Promise.resolve(1)</var> } </pre> @@ -81,14 +81,14 @@ translation_of: Web/JavaScript/Reference/Statements/async_function <p>例如:</p> -<pre class="syntaxbox notranslate">async function <var>foo</var>() { +<pre class="syntaxbox">async function <var>foo</var>() { <var>await 1</var> } </pre> <p>等价于</p> -<pre class="syntaxbox notranslate">function <var>foo</var>() { +<pre class="syntaxbox">function <var>foo</var>() { <var>return Promise.resolve(1).then(() => undefined)</var> } </pre> @@ -103,7 +103,7 @@ translation_of: Web/JavaScript/Reference/Statements/async_function <li>一段时间后,同样当第二个promise完结的时候,<code>result2</code>将被赋值为<code>2</code>,之后函数将会正常同步执行,将默认返回<code>undefined</code> 。</li> </ol> -<pre class="notranslate">async function <var>foo</var>() { +<pre>async function <var>foo</var>() { const result1 = <var>await new Promise((resolve) => setTimeout(() => resolve('1'))) </var> const result2 = <var>await new Promise((resolve) => setTimeout(() => resolve('2')))</var> } @@ -113,7 +113,7 @@ foo()</pre> <p>例如,在下面的代码中,在promise链上配置了<code>.catch</code>处理程序,将抛出未处理的promise错误。这是因为<code>p2</code>返回的结果不会被await处理。</p> -<pre class="notranslate">async function <var>foo</var>() { +<pre>async function <var>foo</var>() { const p1 = <var>new Promise((resolve) => setTimeout(() => resolve('1'), 1000)) </var> const p2 = <var>new Promise((_,reject) => setTimeout(() => reject('2'), 500)) const results = [await p1, await p2] // 不推荐使用这种方式,请使用 Promise.all或者Promise.allSettled </var> @@ -126,7 +126,7 @@ foo().catch(() => {}) // 捕捉所有的错误...</pre> <h3 id="简单例子">简单例子</h3> -<pre class="brush: js notranslate">var resolveAfter2Seconds = function() { +<pre class="brush: js">var resolveAfter2Seconds = function() { console.log("starting slow promise"); return new Promise(resolve => { setTimeout(function() { @@ -238,7 +238,7 @@ setTimeout(parallelPromise, 13000); // same as parallel <p>返回 {{jsxref("Promise")}}的 API 将会产生一个 promise 链,它将函数肢解成许多部分。例如下面的代码:</p> -<pre class="brush: js notranslate">function getProcessedData(url) { +<pre class="brush: js">function getProcessedData(url) { return downloadData(url) // 返回一个 promise 对象 .catch(e => { return downloadFallbackData(url) // 返回一个 promise 对象 @@ -250,7 +250,7 @@ setTimeout(parallelPromise, 13000); // same as parallel <p>可以重写为单个async函数:</p> -<pre class="brush: js notranslate">async function getProcessedData(url) { +<pre class="brush: js">async function getProcessedData(url) { let v; try { v = await downloadData(url); @@ -270,7 +270,7 @@ setTimeout(parallelPromise, 13000); // same as parallel <p>看下下面重写的上面代码,在<code>processDataInWorker</code>抛出异常时返回了null:</p> -<pre class="notranslate"><code>async function getProcessedData(url) { +<pre><code>async function getProcessedData(url) { let v; try { v = await downloadData(url); diff --git a/files/zh-cn/web/javascript/reference/statements/break/index.html b/files/zh-cn/web/javascript/reference/statements/break/index.html index 25d8964e32..c0297dbb86 100644 --- a/files/zh-cn/web/javascript/reference/statements/break/index.html +++ b/files/zh-cn/web/javascript/reference/statements/break/index.html @@ -14,7 +14,7 @@ translation_of: Web/JavaScript/Reference/Statements/break <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate"><code>break [label];</code></pre> +<pre class="syntaxbox"><code>break [label];</code></pre> <dl> <dt><code>label</code> {{optional_inline}}</dt> @@ -33,7 +33,7 @@ translation_of: Web/JavaScript/Reference/Statements/break <p>下面的函数里有个 <code>break</code> 语句,当 <code>i</code> 为 3 时,会中止 {{jsxref("Statements/while", "while")}} 循环,然后返回 3 * <code>x</code> 的值。</p> -<pre class="brush: js notranslate"><code class="language-js">function testBreak(x) { +<pre class="brush: js"><code class="language-js">function testBreak(x) { var i = 0; while (i < 6) { @@ -50,7 +50,7 @@ translation_of: Web/JavaScript/Reference/Statements/break <p>在下面的代码中, <code>break</code> 使用在 {{jsxref("Statements/switch", "switch")}} 语句中,当遇到匹配到case后,就会执行相应的代码并中断循环体。</p> -<pre class="notranslate">const food = "sushi"; +<pre>const food = "sushi"; switch (food) { case "sushi": @@ -68,7 +68,7 @@ switch (food) { <p>下面的代码中一起使用 <code>break</code> 语句和被标记的块语句。一个 <code>break</code> 语句必须内嵌在它引用的标记中。注意,<code>inner_block</code> 内嵌在 <code>outer_block</code> 中。</p> -<pre class="brush:js;highlight:[1,3,5]; notranslate">outer_block:{ +<pre class="brush:js;highlight:[1,3,5];">outer_block:{ inner_block:{ console.log ('1'); @@ -84,7 +84,7 @@ switch (food) { <p>下面的代码同样使用了 <code>break</code> 语句和被标记的块语句,但是产生了一个语法错误,因为它的 <code>break</code> 语句在 <code>block_1</code> 中,但是引用了 <code>block_2</code>。<code>break</code> 语句必须内嵌在它引用的标签中。</p> -<pre class="brush:js;highlight:[1,3,6]; notranslate">block_1:{ +<pre class="brush:js;highlight:[1,3,6];">block_1:{ console.log ('1'); break block_2; // SyntaxError: label not found } @@ -98,7 +98,7 @@ block_2:{ <p>在下面的代码同样会产生SyntaxError,因为它并没被正确的使用在循环、switch或label语句中。</p> -<pre class="notranslate">function testBreak(x) { +<pre>function testBreak(x) { var i = 0; while (i < 6) { @@ -116,7 +116,7 @@ return i * x; testBreak(1); // SyntaxError: Illegal break statement </pre> -<pre class="notranslate">block_1: { +<pre>block_1: { console.log('1'); ( function() { break block_1; // SyntaxError: Undefined label 'block_1' diff --git a/files/zh-cn/web/javascript/reference/statements/const/index.html b/files/zh-cn/web/javascript/reference/statements/const/index.html index b096efd17f..de8e0c7f39 100644 --- a/files/zh-cn/web/javascript/reference/statements/const/index.html +++ b/files/zh-cn/web/javascript/reference/statements/const/index.html @@ -19,7 +19,7 @@ translation_of: Web/JavaScript/Reference/Statements/const <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">const <em>name1 = <em>value1 [</em>, <em>name2</em> = <em>value2</em><em> [</em>, ... [</em>, <em>nameN</em> = <em>valueN]]]</em>;</pre> +<pre class="syntaxbox">const <em>name1 = <em>value1 [</em>, <em>name2</em> = <em>value2</em><em> [</em>, ... [</em>, <em>nameN</em> = <em>valueN]]]</em>;</pre> <dl> <dt><code>nameN</code></dt> @@ -44,7 +44,7 @@ translation_of: Web/JavaScript/Reference/Statements/const <p>常量在声明的时候可以使用大小写,但通常情况下全部用大写字母。</p> -<pre class="brush: js; notranslate">// 定义常量MY_FAV并赋值7 +<pre class="brush: js;">// 定义常量MY_FAV并赋值7 const MY_FAV = 7; // 报错 - Uncaught TypeError: Assignment to constant variable. @@ -69,7 +69,7 @@ let MY_FAV = 20; <p>注意块作用域的性质很重要</p> -<pre class="brush: js notranslate">if (MY_FAV === 7) { +<pre class="brush: js">if (MY_FAV === 7) { // 没问题,并且创建了一个块作用域变量 MY_FAV // (works equally well with let to declare a block scoped non const variable) let MY_FAV = 20; @@ -87,7 +87,7 @@ console.log('my favorite number is ' + MY_FAV); <h3 id="常量要求一个初始值">常量要求一个初始值</h3> -<pre class="brush: js notranslate">// 报错 +<pre class="brush: js">// 报错 // Uncaught SyntaxError: Missing initializer in const declaration const FOO; @@ -97,7 +97,7 @@ const FOO; <p>常量可以定义成对象和数组</p> -<pre class="brush: js notranslate">const MY_OBJECT = {'key': 'value'}; +<pre class="brush: js">const MY_OBJECT = {'key': 'value'}; // 重写对象和上面一样会失败 // Uncaught TypeError: Assignment to constant variable. diff --git a/files/zh-cn/web/javascript/reference/statements/export/index.html b/files/zh-cn/web/javascript/reference/statements/export/index.html index 2eb0086a2f..f2a8e5a226 100644 --- a/files/zh-cn/web/javascript/reference/statements/export/index.html +++ b/files/zh-cn/web/javascript/reference/statements/export/index.html @@ -24,7 +24,7 @@ translation_of: Web/JavaScript/Reference/Statements/export <li>默认导出(每个模块包含一个)</li> </ol> -<pre class="brush: js notranslate">// 导出单个特性 +<pre class="brush: js">// 导出单个特性 export let <em>name1</em>, <em>name2</em>, …, <em>nameN</em>; // also var, const export let <em>name1</em> = …, <em>name2</em> = …, …, <em>nameN</em>; // also var, const export function FunctionName(){...} @@ -63,7 +63,7 @@ export { default } from …;</pre> <p>命名导出:</p> -<pre class="brush: js notranslate">// 导出事先定义的特性 +<pre class="brush: js">// 导出事先定义的特性 export { myFunction,myVariable }; // 导出单个特性(可以导出var,let, @@ -73,7 +73,7 @@ export function myFunction() { ... };</pre> <p>默认导出:</p> -<pre class="brush: js notranslate">// 导出事先定义的特性作为默认值 +<pre class="brush: js">// 导出事先定义的特性作为默认值 export { myFunction as default }; // 导出单个特性作为默认值 @@ -86,16 +86,16 @@ export default class { .. } <p>但是,可以使用任何名称导入默认导出,例如:</p> -<pre class="brush: js notranslate">// 文件 test.js +<pre class="brush: js">// 文件 test.js let k; export default k = 12; </pre> -<pre class="brush: js notranslate">// 另一个文件 +<pre class="brush: js">// 另一个文件 import m from './test'; // 由于 k 是默认导出,所以可以自由使用 import m 替代 import k console.log(m); // 输出为 12 </pre> <p> 你也可以重命名命名导出以避免命名冲突:</p> -<pre class="brush: js notranslate">export { <var>myFunction</var> as <var>function1</var>,<var> +<pre class="brush: js">export { <var>myFunction</var> as <var>function1</var>,<var> myVariable</var> as variable };</pre> <h3 id="重导出_聚合">重导出 / 聚合</h3> @@ -104,13 +104,13 @@ console.log(m); // 输出为 12 </pre> <p>这个可以使用“export from”语法实现:</p> -<pre class="brush: js notranslate">export { default as function1, +<pre class="brush: js">export { default as function1, function2 } from 'bar.js'; </pre> <p>与之形成对比的是联合使用导入和导出:</p> -<pre class="brush: js notranslate">import { default as function1, +<pre class="brush: js">import { default as function1, function2 } from 'bar.js'; export { function1, function2 }; </pre> @@ -121,14 +121,14 @@ export { function1, function2 }; <p>注意:尽管与import等效,但以下语法在语法上无效:</p> </div> -<pre class="brush: js notranslate">import DefaultExport from 'bar.js'; // 有效的 +<pre class="brush: js">import DefaultExport from 'bar.js'; // 有效的 </pre> -<pre class="brush: js notranslate">export DefaultExport from 'bar.js'; // 无效的</pre> +<pre class="brush: js">export DefaultExport from 'bar.js'; // 无效的</pre> <p>这里正确的做法是重命名这个导出:</p> -<pre class="brush: js notranslate">export { default as DefaultExport } from 'bar.js';</pre> +<pre class="brush: js">export { default as DefaultExport } from 'bar.js';</pre> <h2 id="示例">示例</h2> @@ -136,7 +136,7 @@ export { function1, function2 }; <p>在模块 <code>my-module.js</code> 中,可能包含以下代码:</p> -<pre class="brush: js notranslate">// module "my-module.js" +<pre class="brush: js">// module "my-module.js" function cube(x) { return x * x * x; } @@ -158,7 +158,7 @@ export { cube, foo, graph }; <p>然后,在你的 HTML 页面的顶级模块中:</p> -<pre class="brush: js notranslate">import { cube, foo, graph } from 'my-module.js'; +<pre class="brush: js">import { cube, foo, graph } from 'my-module.js'; graph.options = { color:'blue', @@ -180,7 +180,7 @@ console.log(foo); // 4.555806215962888</pre> <p>如果我们要导出一个值或得到模块中的返回值,就可以使用默认导出:</p> -<pre class="brush: js notranslate">// module "my-module.js" +<pre class="brush: js">// module "my-module.js" export default function cube(x) { return x * x * x; @@ -189,7 +189,7 @@ export default function cube(x) { <p>然后,在另一个脚本中,可以直接导入默认导出:</p> -<pre class="brush: js notranslate">import cube from './my-module.js'; +<pre class="brush: js">import cube from './my-module.js'; console.log(cube(3)); // 27 </pre> @@ -206,24 +206,24 @@ console.log(cube(3)); // 27 <p>你的代码看起来应该像这样:</p> -<pre class="brush: js notranslate">// childModule1.js 中 +<pre class="brush: js">// childModule1.js 中 let myFunction = ...; // assign something useful to myFunction let myVariable = ...; // assign something useful to myVariable export {myFunction, myVariable};</pre> -<pre class="brush: js notranslate">// childModule2.js 中 +<pre class="brush: js">// childModule2.js 中 let myClass = ...; // assign something useful to myClass export myClass; </pre> -<pre class="brush: js notranslate">// parentModule.js 中 +<pre class="brush: js">// parentModule.js 中 // 仅仅聚合 childModule1 和 childModule2 中的导出 // 以重新导出他们 export { myFunction, myVariable } from 'childModule1.js'; export { myClass } from 'childModule2.js'; </pre> -<pre class="brush: js notranslate">// 顶层模块中 +<pre class="brush: js">// 顶层模块中 // 我们可以从单个模块调用所有导出,因为 parentModule 事先 // 已经将他们“收集”/“打包”到一起 import { myFunction, myVariable, myClass } from 'parentModule.js' diff --git a/files/zh-cn/web/javascript/reference/statements/for-await...of/index.html b/files/zh-cn/web/javascript/reference/statements/for-await...of/index.html index 247677e1b9..597426a1fc 100644 --- a/files/zh-cn/web/javascript/reference/statements/for-await...of/index.html +++ b/files/zh-cn/web/javascript/reference/statements/for-await...of/index.html @@ -28,7 +28,7 @@ translation_of: Web/JavaScript/Reference/Statements/for-await...of <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">for await (<em>variable</em> of <em>iterable</em>) { +<pre class="syntaxbox">for await (<em>variable</em> of <em>iterable</em>) { <em>statement </em>} </pre> @@ -46,7 +46,7 @@ translation_of: Web/JavaScript/Reference/Statements/for-await...of <p>你还可以迭代一个明确实现异步迭代协议的对象:</p> -<pre class="brush:js notranslate">var asyncIterable = { +<pre class="brush:js">var asyncIterable = { [Symbol.asyncIterator]() { return { i: 0, @@ -76,7 +76,7 @@ translation_of: Web/JavaScript/Reference/Statements/for-await...of <p>异步生成器已经实现了异步迭代器协议, 所以可以用 <code>for await...of</code>循环。</p> -<pre class="brush: js notranslate">async function* asyncGenerator() { +<pre class="brush: js">async function* asyncGenerator() { var i = 0; while (i < 3) { yield i++; @@ -94,7 +94,7 @@ translation_of: Web/JavaScript/Reference/Statements/for-await...of <p>有关使用<code>for await... of</code>考虑迭代API中获取数据的异步 generator 更具体的例子。这个例子首先为一个数据流创建了一个异步 generator,然后使用它来获得这个API的响应值的大小。</p> -<pre class="brush: js notranslate">async function* streamAsyncIterator(stream) { +<pre class="brush: js">async function* streamAsyncIterator(stream) { const reader = stream.getReader(); try { while (true) { diff --git a/files/zh-cn/web/javascript/reference/statements/for...in/index.html b/files/zh-cn/web/javascript/reference/statements/for...in/index.html index 7254cda762..b1ec38f6ef 100644 --- a/files/zh-cn/web/javascript/reference/statements/for...in/index.html +++ b/files/zh-cn/web/javascript/reference/statements/for...in/index.html @@ -12,7 +12,7 @@ translation_of: Web/JavaScript/Reference/Statements/for...in <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="notranslate">for (<var>variable</var> in <var>object</var>) +<pre>for (<var>variable</var> in <var>object</var>) statement</pre> <dl> @@ -47,7 +47,7 @@ translation_of: Web/JavaScript/Reference/Statements/for...in <p>下面的函数接受一个对象作为参数。被调用时迭代传入对象的所有可枚举属性然后返回一个所有属性名和其对应值的字符串。</p> -<pre class="brush: js notranslate">var obj = {a:1, b:2, c:3}; +<pre class="brush: js">var obj = {a:1, b:2, c:3}; for (var prop in obj) { console.log("obj." + prop + " = " + obj[prop]); @@ -60,7 +60,7 @@ for (var prop in obj) { <p>下面的函数说明了{{jsxref("Object.prototype.hasOwnProperty", "hasOwnProperty()")}}的用法:继承的属性不显示。</p> -<pre class="brush: js notranslate">var triangle = {a: 1, b: 2, c: 3}; +<pre class="brush: js">var triangle = {a: 1, b: 2, c: 3}; function ColoredTriangle() { this.color = 'red'; @@ -124,7 +124,7 @@ for (var prop in obj) { <p>在 SpiderMonkey 40 {{geckoRelease(40)}} 版本之前,可以在使用一个初始化表达式(<code>i=0</code>)在一个<code>for...in</code>循环中:</p> -<pre class="brush: js example-bad notranslate">var obj = {a: 1, b: 2, c: 3}; +<pre class="brush: js example-bad">var obj = {a: 1, b: 2, c: 3}; for (var i = 0 in obj) { console.log(obj[i]); } diff --git a/files/zh-cn/web/javascript/reference/statements/function/index.html b/files/zh-cn/web/javascript/reference/statements/function/index.html index dc052a53d0..0ab978503d 100644 --- a/files/zh-cn/web/javascript/reference/statements/function/index.html +++ b/files/zh-cn/web/javascript/reference/statements/function/index.html @@ -21,7 +21,7 @@ translation_of: Web/JavaScript/Reference/Statements/function <h2 id="语法">语法</h2> -<pre class="eval notranslate">function <em>name</em>([<em>param</em>,[, <em>param</em>,[..., <em>param</em>]]]) { +<pre class="eval">function <em>name</em>([<em>param</em>,[, <em>param</em>,[..., <em>param</em>]]]) { [<em>statements</em>] } </pre> @@ -55,7 +55,7 @@ translation_of: Web/JavaScript/Reference/Statements/function <p>函数可以被有条件来声明,这意味着,函数声明可能出现在一个 if 语句里,但是,这种声明方式在不同的浏览器里可能有不同的效果。因此,不应该在生产环境代码中使用这种声明方式,应该使用函数表达式来代替。</p> -<pre class="brush: js notranslate"><code>var hoisted = "foo" in this; +<pre class="brush: js"><code>var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (false) { function foo(){ return 1; } @@ -75,7 +75,7 @@ if (false) { <p>注意,即使把上面代码中的 if(false) 改为 if(true),结果也是一样的</p> -<pre class="brush: js notranslate"><code>var hoisted = "foo" in this; +<pre class="brush: js"><code>var hoisted = "foo" in this; console.log(`'foo' name ${hoisted ? "is" : "is not"} hoisted. typeof foo is ${typeof foo}`); if (true) { function foo(){ return 1; } @@ -98,7 +98,7 @@ if (true) { <p>JavaScript 中的<strong>函数声明</strong>被提升到了<strong>函数定义</strong>。你可以在函数声明之前使用该函数:</p> -<pre class="brush: js language-js notranslate"><code class="language-js" style="direction: ltr; white-space: pre;">hoisted(); // logs "foo" +<pre class="brush: js language-js"><code class="language-js" style="direction: ltr; white-space: pre;">hoisted(); // logs "foo" function hoisted() { console.log('foo'); @@ -109,7 +109,7 @@ function hoisted() { <p>注意 :<strong>函数表达式</strong>{{jsxref("Operators/function", "function expressions")}} 不会被提升:</p> </div> -<pre class="brush: js language-js notranslate"><code class="language-js" style="direction: ltr; white-space: pre;">notHoisted(); // TypeError: notHoisted is not a function +<pre class="brush: js language-js"><code class="language-js" style="direction: ltr; white-space: pre;">notHoisted(); // TypeError: notHoisted is not a function var notHoisted = function() { console.log('bar'); @@ -122,7 +122,7 @@ var notHoisted = function() { <p>下面的代码声明了一个函数,该函数返回了销售的总金额, 参数是产品a,b,c分别的销售的数量.</p> -<pre class="brush: js language-js notranslate"><code class="language-js" style="direction: ltr; white-space: pre;">function calc_sales(units_a, units_b, units_c) {functionfunctionfunctionfunctionfunctionfunctionfunctionfunctionfunctionfunctionfunction +<pre class="brush: js language-js"><code class="language-js" style="direction: ltr; white-space: pre;">function calc_sales(units_a, units_b, units_c) {functionfunctionfunctionfunctionfunctionfunctionfunctionfunctionfunctionfunctionfunction return units_a*79 + units_b * 129 + units_c * 699; }</code></pre> diff --git a/files/zh-cn/web/javascript/reference/statements/import/index.html b/files/zh-cn/web/javascript/reference/statements/import/index.html index eac05517ff..8daa4187e2 100644 --- a/files/zh-cn/web/javascript/reference/statements/import/index.html +++ b/files/zh-cn/web/javascript/reference/statements/import/index.html @@ -21,7 +21,7 @@ translation_of: Web/JavaScript/Reference/Statements/import <p>语法</p> -<pre class="syntaxbox brush: js notranslate">import <em>defaultExport</em> from "<em>module-name</em>"; +<pre class="syntaxbox brush: js">import <em>defaultExport</em> from "<em>module-name</em>"; import * as <em>name</em> from "<em>module-name</em>"; import { <em>export </em>} from "<em>module-name</em>"; import { <em>export</em> as <em>alias </em>} from "<em>module-name</em>"; @@ -55,37 +55,37 @@ var promise = import("module-name");//这是一个处于第三阶段的提案。 <p>这将<code>myModule</code>插入当前作用域,其中包含来自位于<code>/modules/my-module.js</code>文件中导出的所有接口。</p> -<pre class="brush: js notranslate">import * as myModule from '/modules/my-module.js'; +<pre class="brush: js">import * as myModule from '/modules/my-module.js'; </pre> <p>在这里,访问导出接口意味着使用模块名称(在本例为“myModule”)作为命名空间。例如,如果上面导入的模块包含一个接口<code>doAllTheAmazingThings()</code>,你可以这样调用:</p> -<pre class="brush: js notranslate">myModule.doAllTheAmazingThings();</pre> +<pre class="brush: js">myModule.doAllTheAmazingThings();</pre> <h3 id="导入单个接口">导入单个接口</h3> <p>给定一个名为<code>myExport</code>的对象或值,它已经从模块<code>my-module</code>导出(因为整个模块被导出)或显式地导出(使用{{jsxref("Statements/export", "export")}}语句),将<code>myExport</code>插入当前作用域。</p> -<pre class="brush: js notranslate">import {myExport} from '/modules/my-module.js';</pre> +<pre class="brush: js">import {myExport} from '/modules/my-module.js';</pre> <h3 id="导入多个接口">导入多个接口</h3> <p>这将<code>foo</code>和<code>bar</code>插入当前作用域。</p> -<pre class="brush: js notranslate">import {foo, bar} from '/modules/my-module.js';</pre> +<pre class="brush: js">import {foo, bar} from '/modules/my-module.js';</pre> <h3 id="导入带有别名的接口">导入带有别名的接口</h3> <p>你可以在导入时重命名接口。例如,将<code>shortName</code>插入当前作用域。</p> -<pre class="brush: js notranslate">import {reallyReallyLongModuleExportName as shortName} +<pre class="brush: js">import {reallyReallyLongModuleExportName as shortName} from '/modules/my-module.js';</pre> <h3 id="导入时重命名多个接口">导入时重命名多个接口</h3> <p>使用别名导入模块的多个接口。</p> -<pre class="brush: js notranslate">import { +<pre class="brush: js">import { reallyReallyLongModuleMemberName as shortName, anotherLongModuleName as short } from '/modules/my-module.js'; @@ -95,7 +95,7 @@ var promise = import("module-name");//这是一个处于第三阶段的提案。 <p>整个模块仅为副作用(中性词,无贬义含义)而导入,而不导入模块中的任何内容(接口)。 这将运行模块中的全局代码, 但实际上不导入任何值。</p> -<pre class="brush: js notranslate">import '/modules/my-module.js';</pre> +<pre class="brush: js">import '/modules/my-module.js';</pre> <h3 id="导入默认值">导入默认值</h3> @@ -103,22 +103,22 @@ var promise = import("module-name");//这是一个处于第三阶段的提案。 <p>最简单的用法是直接导入默认值:</p> -<pre class="brush: js notranslate">import myDefault from '/modules/my-module.js';</pre> +<pre class="brush: js">import myDefault from '/modules/my-module.js';</pre> <p>也可以同时将<code>default</code>语法与上述用法(命名空间导入或命名导入)一起使用。在这种情况下,<code>default</code>导入必须首先声明。 例如:</p> -<pre class="brush: js notranslate">import myDefault, * as myModule from '/modules/my-module.js'; +<pre class="brush: js">import myDefault, * as myModule from '/modules/my-module.js'; // myModule used as a namespace</pre> <p>或者</p> -<pre class="brush: js notranslate">import myDefault, {foo, bar} from '/modules/my-module.js'; +<pre class="brush: js">import myDefault, {foo, bar} from '/modules/my-module.js'; // specific, named imports </pre> <p>当用{{anch("动态导入")}}的方式导入默认导出时,其工作方式有所不同。你需要从返回的对象中解构并重命名 "default" 键。</p> -<pre class="brush: js notranslate">(async () => { +<pre class="brush: js">(async () => { if (somethingIsTrue) { const { default: myDefault, foo, bar } = await import('/modules/my-module.js'); } @@ -140,7 +140,7 @@ var promise = import("module-name");//这是一个处于第三阶段的提案。 <p>关键字import可以像调用函数一样来动态的导入模块。以这种方式调用,将返回一个 <code>promise</code>。</p> -<pre class="brush: js notranslate">import('/modules/my-module.js') +<pre class="brush: js">import('/modules/my-module.js') .then((module) => { // Do something with the module. }); @@ -148,7 +148,7 @@ var promise = import("module-name");//这是一个处于第三阶段的提案。 <p>这种使用方式也支持 <code>await</code> 关键字。</p> -<pre class="brush: js notranslate">let module = await import('/modules/my-module.js');</pre> +<pre class="brush: js">let module = await import('/modules/my-module.js');</pre> <h2 id="示例">示例</h2> @@ -158,7 +158,7 @@ var promise = import("module-name");//这是一个处于第三阶段的提案。 <h4 id="模块:file.js">模块:file.js</h4> -<pre class="brush: js notranslate">function getJSON(url, callback) { +<pre class="brush: js">function getJSON(url, callback) { let xhr = new XMLHttpRequest(); xhr.onload = function () { callback(this.responseText) @@ -173,7 +173,7 @@ export function getUsefulContents(url, callback) { <h4 id="主程序:main.js">主程序:main.js</h4> -<pre class="brush: js notranslate">import { getUsefulContents } from '/modules/file.js'; +<pre class="brush: js">import { getUsefulContents } from '/modules/file.js'; getUsefulContents('http://www.example.com', data => { doSomethingUseful(data); });</pre> @@ -182,7 +182,7 @@ getUsefulContents('http://www.example.com', <p>此示例展示了如何基于用户操作去加载功能模块到页面上,在例子中通过点击按钮,然后会调用模块内的函数。当然这不是能实现这个功能的唯一方式,<code>import()</code>函数也可以支持<code>await</code>。</p> -<pre class="brush: js notranslate">const main = document.querySelector("main"); +<pre class="brush: js">const main = document.querySelector("main"); for (const link of document.querySelectorAll("nav > a")) { link.addEventListener("click", e => { e.preventDefault(); diff --git a/files/zh-cn/web/javascript/reference/statements/let/index.html b/files/zh-cn/web/javascript/reference/statements/let/index.html index 84898ef237..0dc1a84365 100644 --- a/files/zh-cn/web/javascript/reference/statements/let/index.html +++ b/files/zh-cn/web/javascript/reference/statements/let/index.html @@ -23,7 +23,7 @@ translation_of: Web/JavaScript/Reference/Statements/let <h2 id="语法">语法</h2> -<pre class="syntaxbox notranslate">let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];</pre> +<pre class="syntaxbox">let var1 [= value1] [, var2 [= value2]] [, ..., varN [= valueN]];</pre> <h3 id="参数">参数</h3> @@ -46,7 +46,7 @@ translation_of: Web/JavaScript/Reference/Statements/let <p><code><strong>let</strong></code>声明的变量只在其声明的块或子块中可用,这一点,与<code><strong>var</strong></code>相似。二者之间最主要的区别在于<code><strong>var</strong></code>声明的变量的作用域是整个封闭函数。</p> -<pre class="brush: js notranslate">function varTest() { +<pre class="brush: js">function varTest() { var x = 1; { var x = 2; // 同样的变量! @@ -69,7 +69,7 @@ function letTest() { <p>位于函数或代码顶部的<strong><code>var</code></strong>声明会给全局对象新增属性, 而<strong><code>let</code></strong>不会。例如:</p> -<pre class="brush: js notranslate">var x = 'global'; +<pre class="brush: js">var x = 'global'; let y = 'global'; console.log(this.x); // "global" console.log(this.y); // undefined @@ -79,7 +79,7 @@ console.log(this.y); // undefined <p>在处理<a href="https://developer.mozilla.org/en-US/docs/Glossary/Constructor">构造函数</a>的时候,可以通过<code><strong>let</strong></code>声明而不是闭包来创建一个或多个私有成员。</p> -<pre class="brush: js notranslate">var Thing; +<pre class="brush: js">var Thing; { let privateScope = new WeakMap(); @@ -122,7 +122,7 @@ thing.showPrivate(); <p>在同一个函数或块作用域中重复声明同一个变量会引起{{jsxref("SyntaxError")}}。</p> -<pre class="brush: js example-bad notranslate">if (x) { +<pre class="brush: js example-bad">if (x) { let foo; let foo; // SyntaxError thrown. } @@ -130,7 +130,7 @@ thing.showPrivate(); <p>在 <a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/switch"><code>switch</code></a> 语句中只有一个块,你可能因此而遇到错误。</p> -<pre class="brush: js example-bad notranslate">let x = 1; +<pre class="brush: js example-bad">let x = 1; switch(x) { case 0: let foo; @@ -144,7 +144,7 @@ switch(x) { <p>然而,需要特别指出的是,一个嵌套在 case 子句中的块会创建一个新的块作用域的词法环境,就不会产生上诉重复声明的错误。</p> -<pre class="notranslate">let x = 1; +<pre>let x = 1; switch(x) { case 0: { @@ -162,7 +162,7 @@ switch(x) { <p>与通过 <code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting">var</a></code> 声明的有初始化值 <code>undefined</code> 的变量不同,通过 <code>let</code> 声明的变量直到它们的定义被执行时才初始化。在变量初始化前访问该变量会导致 <code><a href="https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/ReferenceError">ReferenceError</a></code>。该变量处在一个自块顶部到初始化处理的“暂存死区”中。</p> -<pre class="brush: js notranslate">function do_something() { +<pre class="brush: js">function do_something() { console.log(bar); // undefined console.log(foo); // ReferenceError var bar = 1; @@ -173,7 +173,7 @@ switch(x) { <p>与通过<code>var</code>声明的变量, 有初始化值 <code>undefined</code>和只是未声明的变量不同的是,如果使用<code>typeof</code>检测在暂存死区中的变量, 会抛出<code>ReferenceError</code>异常:</p> -<pre class="notranslate"><code>// prints out 'undefined' +<pre><code>// prints out 'undefined' console.log(typeof undeclaredVariable); // results in a 'ReferenceError' @@ -189,7 +189,7 @@ let i = 10;</code> <p>这个if块里的<code>foo</code>还依旧在暂存死区里。</p> -<pre class="brush: js example-bad notranslate">function test(){ +<pre class="brush: js example-bad">function test(){ var foo = 33; if (foo) { let foo = (foo + 55); // ReferenceError @@ -201,7 +201,7 @@ test();</pre> <p>在没有执行到它的初始化语句之前,它仍旧存在于暂存死区中。</p> -<pre class="brush: js example-bad notranslate">function go(n) { +<pre class="brush: js example-bad">function go(n) { // n here is defined! console.log(n); // Object {a: [1,2,3]} @@ -216,7 +216,7 @@ go({a: [1, 2, 3]});</pre> <p>用在块级作用域中时, <strong><code>let</code></strong>将变量的作用域限制在块内, 而<code><strong>var</strong></code>声明的变量的作用域是在函数内.</p> -<pre class="brush: js notranslate">var a = 1; +<pre class="brush: js">var a = 1; var b = 2; if (a === 1) { @@ -232,7 +232,7 @@ console.log(b); // 2</pre> <p>而这种<code><strong>var</strong></code> 与 <strong><code>let</code></strong>合并的声明方式会报<code><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SyntaxError">SyntaxError</a></code>错误, 因为<code><strong>var</strong></code>会将变量提升至块的顶部, 这会导致隐式地重复声明变量.</p> -<pre class="brush: js example-bad notranslate">let x = 1; +<pre class="brush: js example-bad">let x = 1; { var x = 2; // SyntaxError for re-declaration diff --git a/files/zh-cn/web/javascript/reference/statements/switch/index.html b/files/zh-cn/web/javascript/reference/statements/switch/index.html index 64cce4f231..763bda116b 100644 --- a/files/zh-cn/web/javascript/reference/statements/switch/index.html +++ b/files/zh-cn/web/javascript/reference/statements/switch/index.html @@ -20,7 +20,7 @@ translation_of: Web/JavaScript/Reference/Statements/switch <h2 id="语法">语法</h2> -<pre class="brush: js notranslate">switch (expression) { +<pre class="brush: js">switch (expression) { case value1: // 当 expression 的结果与 value1 匹配时,执行此处语句 [break;] @@ -59,7 +59,7 @@ translation_of: Web/JavaScript/Reference/Statements/switch <p>下面的例子中,如果 <code>expr</code> 计算为 "Bananas",程序就会匹配值为 "Bananas" 的 case 然后执行相关语句。当遇到 <code>break</code> 时,程序就跳出 <code>switch</code> 然后执行 <code>switch</code> 后的语句。若 <code>break</code> 被省略,值为 "Cherries" 的 case 中的语句就也将被执行。</p> -<pre class="brush: js notranslate">switch (expr) { +<pre class="brush: js">switch (expr) { case 'Oranges': console.log('Oranges are $0.59 a pound.'); break; @@ -87,7 +87,7 @@ console.log("Is there anything else you'd like?"); <p>如果你忘记添加 break,那么代码将会从值所匹配的 case 语句开始运行,然后持续执行下一个 case 语句而不论值是否匹配。例子如下:</p> -<pre class="brush: js notranslate">var foo = 0; +<pre class="brush: js">var foo = 0; switch (foo) { case -1: console.log('negative 1'); @@ -109,7 +109,7 @@ switch (foo) { <p>可以啊!JavaScript 会在它找不到匹配项时跳回到那个 default :</p> -<pre class="brush: js notranslate">var foo = 5; +<pre class="brush: js">var foo = 5; switch (foo) { case 2: console.log(2); @@ -136,7 +136,7 @@ switch (foo) { <p>这是一个单操作顺序的 switch 语句,其中四个不同值的执行结果完全一样。</p> -<pre class="brush: js notranslate">var Animal = 'Giraffe'; +<pre class="brush: js">var Animal = 'Giraffe'; switch (Animal) { case 'Cow': case 'Giraffe': @@ -153,7 +153,7 @@ switch (Animal) { <p>这是一个关联操作顺序的 switch 语句,其中,根据所输入的整数,你会得到不同的输出。这表示它将以你放置 case 语句的顺序遍历,并且不必是数字顺序的。在 JavaScript 中,你甚至可以将字符串定义到这些 case 语句里。</p> -<pre class="brush: js notranslate">var foo = 1; +<pre class="brush: js">var foo = 1; var output = 'Output: '; switch (foo) { case 0: @@ -222,7 +222,7 @@ switch (foo) { <p>以这段代码为例:</p> -<pre class="brush: js notranslate">const action = 'say_hello'; +<pre class="brush: js">const action = 'say_hello'; switch (action) { case 'say_hello': let message = 'hello'; @@ -243,7 +243,7 @@ switch (action) { <p>通过把 case 语句包装到括号里面,我们就可以轻松解决这个问题。</p> -<pre class="brush: js notranslate">const action = 'say_hello'; +<pre class="brush: js">const action = 'say_hello'; switch (action) { case 'say_hello': { // added brackets let message = 'hello'; diff --git a/files/zh-cn/web/javascript/reference/statements/with/index.html b/files/zh-cn/web/javascript/reference/statements/with/index.html index 32ce03679b..4454271872 100644 --- a/files/zh-cn/web/javascript/reference/statements/with/index.html +++ b/files/zh-cn/web/javascript/reference/statements/with/index.html @@ -15,7 +15,7 @@ translation_of: Web/JavaScript/Reference/Statements/with <h2 id="Syntax" name="Syntax">语法</h2> -<pre class="syntaxbox notranslate">with (expression) { +<pre class="syntaxbox">with (expression) { <em>statement</em> } </pre> @@ -43,7 +43,7 @@ translation_of: Web/JavaScript/Reference/Statements/with <p><strong>弊端:</strong><code>with</code>语句使得代码不易阅读,同时使得JavaScript编译器难以在作用域链上查找某个变量,难以决定应该在哪个对象上来取值。请看下面的例子:</p> -<pre class="brush: js notranslate">function f(x, o) { +<pre class="brush: js">function f(x, o) { with (o) print(x); }</pre> @@ -53,7 +53,7 @@ translation_of: Web/JavaScript/Reference/Statements/with <p><strong>弊端:</strong>使用<code>with</code>语句的代码,无法向前兼容,特別是在使用一些原生数据类型的时候。看下面的例子:</p> <div> -<pre class="brush:js notranslate">function f(foo, values) { +<pre class="brush:js">function f(foo, values) { with (foo) { console.log(values) } @@ -69,7 +69,7 @@ translation_of: Web/JavaScript/Reference/Statements/with <p>下面的<code>with</code>语句指定<code><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Math" title="JavaScript/Reference/Global_Objects/Math">Math</a></code>对象作为默认对象。<code>with</code>语句里面的变量,分別指向<code>Math</code>对象的<a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI" title="JavaScript/Reference/Global_Objects/Math/PI"><code>PI</code></a> 、<code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/cos" title="JavaScript/Reference/Global_Objects/Math/cos">cos</a>和</code><code><a href="/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/sin" title="JavaScript/Reference/Global_Objects/Math/sin">sin</a></code>函数,不用在前面添加命名空间。后续所有引用都指向<code>Math</code>对象。</p> -<pre class="brush:js notranslate">var a, x, y; +<pre class="brush:js">var a, x, y; var r = 10; with (Math) { |