From 01b0e12ba27b5069248fd09235e9a7143915ee30 Mon Sep 17 00:00:00 2001 From: Irvin Date: Wed, 16 Feb 2022 02:02:49 +0800 Subject: remove `notranslate` class in zh-CN --- .../web/javascript/reference/classes/index.html | 36 ++++++++-------- .../errors/cyclic_object_value/index.html | 8 ++-- .../reference/errors/not_a_function/index.html | 22 +++++----- .../reference/errors/not_defined/index.html | 10 ++--- .../reference/functions/arguments/index.html | 36 ++++++++-------- .../reference/functions/arrow_functions/index.html | 50 +++++++++++----------- .../global_objects/aggregateerror/index.html | 6 +-- .../global_objects/array/concat/index.html | 10 ++--- .../global_objects/array/every/index.html | 8 ++-- .../global_objects/array/filter/index.html | 12 +++--- .../global_objects/array/findindex/index.html | 6 +-- .../reference/global_objects/array/flat/index.html | 18 ++++---- .../global_objects/array/flatmap/index.html | 10 ++--- .../reference/global_objects/array/from/index.html | 18 ++++---- .../reference/global_objects/array/map/index.html | 24 +++++------ .../global_objects/array/reduce/index.html | 40 ++++++++--------- .../global_objects/array/reduceright/index.html | 20 ++++----- .../global_objects/array/slice/index.html | 14 +++--- .../global_objects/array/values/index.html | 12 +++--- .../global_objects/arraybuffer/index.html | 8 ++-- .../reference/global_objects/atomics/index.html | 8 ++-- .../global_objects/atomics/notify/index.html | 8 ++-- .../global_objects/bigint64array/index.html | 2 +- .../reference/global_objects/boolean/index.html | 12 +++--- .../reference/global_objects/date/index.html | 14 +++--- .../global_objects/encodeuricomponent/index.html | 10 ++--- .../global_objects/finalizationregistry/index.html | 12 +++--- .../global_objects/function/apply/index.html | 18 ++++---- .../global_objects/function/bind/index.html | 16 +++---- .../reference/global_objects/globalthis/index.html | 6 +-- .../reference/global_objects/infinity/index.html | 2 +- .../global_objects/intl/locale/index.html | 4 +- .../intl/relativetimeformat/index.html | 8 ++-- .../global_objects/json/stringify/index.html | 18 ++++---- .../global_objects/map/foreach/index.html | 4 +- .../reference/global_objects/map/keys/index.html | 4 +- .../reference/global_objects/math/floor/index.html | 6 +-- .../global_objects/math/random/index.html | 10 ++--- .../reference/global_objects/math/sin/index.html | 4 +- .../reference/global_objects/math/sinh/index.html | 6 +-- .../global_objects/number/isfinite/index.html | 6 +-- .../global_objects/number/number/index.html | 4 +- .../global_objects/object/assign/index.html | 24 +++++------ .../global_objects/object/create/index.html | 10 ++--- .../object/defineproperties/index.html | 6 +-- .../object/defineproperty/index.html | 24 +++++------ .../global_objects/object/fromentries/index.html | 8 ++-- .../object/getownpropertydescriptor/index.html | 6 +-- .../object/hasownproperty/index.html | 12 +++--- .../reference/global_objects/object/index.html | 10 ++--- .../reference/global_objects/object/is/index.html | 6 +-- .../global_objects/object/issealed/index.html | 6 +-- .../reference/global_objects/parseint/index.html | 18 ++++---- .../global_objects/promise/all/index.html | 14 +++--- .../global_objects/promise/allsettled/index.html | 2 +- .../global_objects/promise/any/index.html | 8 ++-- .../reference/global_objects/promise/index.html | 24 +++++------ .../global_objects/promise/race/index.html | 6 +-- .../reference/global_objects/proxy/index.html | 18 ++++---- .../global_objects/proxy/proxy/index.html | 4 +- .../proxy/proxy/preventextensions/index.html | 6 +-- .../global_objects/reflect/construct/index.html | 10 ++--- .../reflect/defineproperty/index.html | 6 +-- .../reference/global_objects/reflect/index.html | 6 +-- .../reference/global_objects/regexp/index.html | 20 ++++----- .../global_objects/regexp/regexp/index.html | 4 +- .../global_objects/regexp/test/index.html | 8 ++-- .../global_objects/set/@@iterator/index.html | 6 +-- .../global_objects/set/@@species/index.html | 4 +- .../reference/global_objects/set/add/index.html | 4 +- .../reference/global_objects/set/index.html | 12 +++--- .../reference/global_objects/set/set/index.html | 4 +- .../reference/global_objects/set/values/index.html | 4 +- .../global_objects/string/charcodeat/index.html | 8 ++-- .../global_objects/string/concat/index.html | 4 +- .../global_objects/string/endswith/index.html | 6 +-- .../global_objects/string/fromcharcode/index.html | 6 +-- .../global_objects/string/includes/index.html | 8 ++-- .../global_objects/string/indexof/index.html | 18 ++++---- .../global_objects/string/localecompare/index.html | 10 ++--- .../global_objects/string/match/index.html | 10 ++--- .../global_objects/string/matchall/index.html | 14 +++--- .../global_objects/string/padend/index.html | 6 +-- .../global_objects/string/padstart/index.html | 6 +-- .../global_objects/string/repeat/index.html | 6 +-- .../global_objects/string/replace/index.html | 22 +++++----- .../global_objects/string/replaceall/index.html | 8 ++-- .../global_objects/string/search/index.html | 4 +- .../global_objects/string/startswith/index.html | 6 +-- .../global_objects/string/substring/index.html | 10 ++--- .../global_objects/string/tolowercase/index.html | 4 +- .../global_objects/string/touppercase/index.html | 6 +-- .../global_objects/string/trim/index.html | 6 +-- .../global_objects/string/valueof/index.html | 4 +- .../global_objects/symbol/hasinstance/index.html | 2 +- .../reference/global_objects/symbol/index.html | 18 ++++---- .../global_objects/symbol/keyfor/index.html | 4 +- .../global_objects/symbol/search/index.html | 2 +- .../global_objects/symbol/split/index.html | 4 +- .../global_objects/typedarray/foreach/index.html | 4 +- .../global_objects/typedarray/set/index.html | 4 +- .../global_objects/uint16array/index.html | 2 +- .../global_objects/uint8clampedarray/index.html | 8 ++-- .../reference/global_objects/unescape/index.html | 4 +- .../global_objects/weakref/deref/index.html | 4 +- .../reference/global_objects/weakref/index.html | 2 +- .../global_objects/webassembly/global/index.html | 2 +- .../global_objects/webassembly/instance/index.html | 2 +- .../global_objects/webassembly/table/index.html | 8 ++-- .../reference/iteration_protocols/index.html | 30 ++++++------- .../reference/operators/addition/index.html | 6 +-- .../operators/addition_assignment/index.html | 4 +- .../reference/operators/assignment/index.html | 4 +- .../reference/operators/await/index.html | 8 ++-- .../reference/operators/bitwise_and/index.html | 8 ++-- .../operators/bitwise_and_assignment/index.html | 4 +- .../reference/operators/bitwise_not/index.html | 8 ++-- .../reference/operators/bitwise_or/index.html | 8 ++-- .../operators/bitwise_or_assignment/index.html | 4 +- .../reference/operators/bitwise_xor/index.html | 8 ++-- .../operators/bitwise_xor_assignment/index.html | 4 +- .../reference/operators/decrement/index.html | 6 +-- .../reference/operators/delete/index.html | 28 ++++++------ .../reference/operators/division/index.html | 6 +-- .../operators/division_assignment/index.html | 4 +- .../reference/operators/equality/index.html | 12 +++--- .../reference/operators/exponentiation/index.html | 12 +++--- .../operators/exponentiation_assignment/index.html | 4 +- .../reference/operators/greater_than/index.html | 12 +++--- .../operators/greater_than_or_equal/index.html | 12 +++--- .../javascript/reference/operators/in/index.html | 14 +++--- .../reference/operators/increment/index.html | 6 +-- .../reference/operators/inequality/index.html | 14 +++--- .../reference/operators/instanceof/index.html | 12 +++--- .../reference/operators/left_shift/index.html | 6 +-- .../operators/left_shift_assignment/index.html | 4 +- .../reference/operators/less_than/index.html | 12 +++--- .../operators/less_than_or_equal/index.html | 12 +++--- .../reference/operators/logical_and/index.html | 20 ++++----- .../operators/logical_and_assignment/index.html | 8 ++-- .../reference/operators/logical_not/index.html | 10 ++--- .../logical_nullish_assignment/index.html | 8 ++-- .../reference/operators/logical_or/index.html | 20 ++++----- .../reference/operators/multiplication/index.html | 8 ++-- .../operators/multiplication_assignment/index.html | 4 +- .../javascript/reference/operators/new/index.html | 20 ++++----- .../nullish_coalescing_operator/index.html | 18 ++++---- .../operators/optional_chaining/index.html | 28 ++++++------ .../reference/operators/remainder/index.html | 8 ++-- .../operators/remainder_assignment/index.html | 4 +- .../reference/operators/right_shift/index.html | 8 ++-- .../operators/right_shift_assignment/index.html | 4 +- .../reference/operators/spread_syntax/index.html | 36 ++++++++-------- .../reference/operators/strict_equality/index.html | 8 ++-- .../operators/strict_inequality/index.html | 12 +++--- .../reference/operators/subtraction/index.html | 6 +-- .../operators/subtraction_assignment/index.html | 4 +- .../reference/operators/super/index.html | 12 +++--- .../javascript/reference/operators/this/index.html | 46 ++++++++++---------- .../reference/operators/typeof/index.html | 20 ++++----- .../reference/operators/unary_negation/index.html | 6 +-- .../reference/operators/unary_plus/index.html | 6 +-- .../operators/unsigned_right_shift/index.html | 8 ++-- .../unsigned_right_shift_assignment/index.html | 4 +- .../reference/statements/async_function/index.html | 22 +++++----- .../reference/statements/break/index.html | 14 +++--- .../reference/statements/const/index.html | 10 ++--- .../reference/statements/export/index.html | 38 ++++++++-------- .../reference/statements/for-await...of/index.html | 8 ++-- .../reference/statements/for...in/index.html | 8 ++-- .../reference/statements/function/index.html | 12 +++--- .../reference/statements/import/index.html | 34 +++++++-------- .../javascript/reference/statements/let/index.html | 26 +++++------ .../reference/statements/switch/index.html | 16 +++---- .../reference/statements/with/index.html | 8 ++-- 175 files changed, 948 insertions(+), 948 deletions(-) (limited to 'files/zh-cn/web/javascript/reference') 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

定义类的一种方法是使用类声明。要声明一个类,你可以使用带有class关键字的类名(这里是“Rectangle”)。

-
class Rectangle {
+
class Rectangle {
   constructor(height, width) {
     this.height = height;
     this.width = width;
@@ -37,7 +37,7 @@ translation_of: Web/JavaScript/Reference/Classes
 
 

函数声明类声明之间的一个重要区别在于, 函数声明会{{Glossary("Hoisting", "提升")}},类声明不会。你首先需要声明你的类,然后再访问它,否则类似以下的代码将抛出{{jsxref("ReferenceError")}}:

-
let p = new Rectangle(); // ReferenceError
+
let p = new Rectangle(); // ReferenceError
 
 class Rectangle {}
 
@@ -46,7 +46,7 @@ class Rectangle {}

类表达式是定义类的另一种方法。类表达式可以命名或不命名。命名类表达式的名称是该类体的局部名称。(不过,可以通过类的(而不是一个实例的) {{jsxref("Function.name", "name")}} 属性来检索它)。

-
// 未命名/匿名类
+
// 未命名/匿名类
 let Rectangle = class {
   constructor(height, width) {
     this.height = height;
@@ -88,7 +88,7 @@ console.log(Rectangle.name);
 
 

参见方法定义

-
class Rectangle {
+
class Rectangle {
     // constructor
     constructor(height, width) {
         this.height = height;
@@ -113,7 +113,7 @@ console.log(square.area);
 
 

static 关键字用来定义一个类的一个静态方法。调用静态方法不需要实例化该类,但不能通过一个类实例调用静态方法。静态方法通常用于为一个应用程序创建工具函数。

-
class Point {
+
class Point {
     constructor(x, y) {
         this.x = x;
         this.y = y;
@@ -145,7 +145,7 @@ console.log(Point.distance(p1, p2));
 
 

当调用静态或原型方法时没有指定 this 的值,那么方法内的 this 值将被置为 undefined。即使你未设置 "use strict" ,因为 class 体内部的代码总是在严格模式下执行。

-
class Animal {
+
class Animal {
   speak() {
     return this;
   }
@@ -167,7 +167,7 @@ eat(); // undefined

严格模式下不会发生自动装箱,this 值将保留传入状态。

-
function Animal() { }
+
function Animal() { }
 
 Animal.prototype.speak = function() {
   return this;
@@ -189,7 +189,7 @@ eat(); // global object
 
 

实例的属性必须定义在类的方法里:

-
class Rectangle {
+
class Rectangle {
   constructor(height, width) {
     this.height = height;
     this.width = width;
@@ -199,7 +199,7 @@ eat(); // global object
 
 

静态的或原型的数据属性必须定义在类定义的外面。

-
Rectangle.staticWidth = 20;
+
Rectangle.staticWidth = 20;
 Rectangle.prototype.prototypeWidth = 25;
 
@@ -213,7 +213,7 @@ Rectangle.prototype.prototypeWidth = 25;

使用JavaScript字段声明语法,上面的示例可以写成:

-
class Rectangle {
+
class Rectangle {
   height = 0;
   width;
   constructor(height, width) {
@@ -231,7 +231,7 @@ Rectangle.prototype.prototypeWidth = 25;
 
 

使用私有字段,可以按以下方式细化定义。

-
class Rectangle {
+
class Rectangle {
   #height = 0;
   #width;
   constructor(height, width) {
@@ -255,7 +255,7 @@ Rectangle.prototype.prototypeWidth = 25;
 
 

extends 关键字在 类声明 或 类表达式 中用于创建一个类作为另一个类的一个子类。

-
class Animal {
+
class Animal {
   constructor(name) {
     this.name = name;
   }
@@ -283,7 +283,7 @@ d.speak();// 'Mitzie barks.'
 
 

也可以继承传统的基于函数的“类”:

-
function Animal (name) {
+
function Animal (name) {
   this.name = name;
 }
 Animal.prototype.speak = function () {
@@ -302,7 +302,7 @@ d.speak();//Mitzie makes a noise.  Mitzie barks.

请注意,类不能继承常规对象(不可构造的)。如果要继承常规对象,可以改用{{jsxref("Object.setPrototypeOf()")}}:

-
var Animal = {
+
var Animal = {
   speak() {
     console.log(this.name + ' makes a noise.');
   }
@@ -325,7 +325,7 @@ d.speak(); // Mitzie makes a noise.

例如,当使用像{{jsxref("Array.map", "map()")}}返回默认构造函数的方法时,您希望这些方法返回一个父Array对象,而不是MyArray对象。{{jsxref("Symbol.species")}} 符号可以让你这样做:

-
class MyArray extends Array {
+
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);
 
 

super 关键字用于调用对象的父对象上的函数。

-
class Cat {
+
class Cat {
   constructor(name) {
     this.name = name;
   }
@@ -366,7 +366,7 @@ class Lion extends Cat {
 
 

一个以超类作为输入的函数和一个继承该超类的子类作为输出可以用于在ECMAScript中实现混合:

-
var calculatorMixin = Base => class extends Base {
+
var calculatorMixin = Base => class extends Base {
   calc() { }
 };
 
@@ -376,7 +376,7 @@ var randomizerMixin = Base => class extends Base {
 
 

使用 mix-ins 的类可以像下面这样写:

-
class Foo { }
+
class Foo { }
 class Bar extends calculatorMixin(randomizerMixin(Foo)) { }

规范

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

提示信息

-
TypeError: cyclic object value (Firefox)
+
TypeError: cyclic object value (Firefox)
 TypeError: Converting circular structure to JSON (Chrome and Opera)
 TypeError: Circular reference in value argument not supported (Edge)
@@ -34,7 +34,7 @@ TypeError: Circular reference in value argument not supported (Edge)

在如下循环结构中:

-
var a = {};
+
var a = {};
 var b = {};
 a.child = b;
 b.child = a;
@@ -42,7 +42,7 @@ b.child = a;
 
 

{{jsxref("JSON.stringify()")}} 将会报错

-
JSON.stringify(a);
+
JSON.stringify(a);
 // TypeError: cyclic object value
 
@@ -52,7 +52,7 @@ b.child = a;

注意:以下代码并不会保存循环引用的值。

-
var seen = [];
+
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
 
 

信息

-
TypeError: Object doesn't support property or method {x} (Edge)
+
TypeError: Object doesn't support property or method {x} (Edge)
 TypeError: "x" is not a function

错误类型

@@ -47,20 +47,20 @@ TypeError: "x" is not a function

函数的名称拼写错误,这种情况是经常发生的:

-
var x = document.getElementByID("foo");
+
var x = document.getElementByID("foo");
 // TypeError: document.getElementByID is not a function
 

正确的方法名应该是 getElementById:

-
var x = document.getElementById("foo");
+
var x = document.getElementById("foo");
 

调用Object类型中不存在的方法

对于某些特殊的方法,它只属于某些特定的原生对象中,你必须提供一个回调函数才能正常运行。例如:这里调用了一个 {{jsxref("Array.prototype.map()")}} 方法,但是这方法只能被 {{jsxref("Array")}} 对象所调用。 

-
var obj = { a: 13, b: 37, c: 42 };
+
var obj = { a: 13, b: 37, c: 42 };
 
 obj.map(function(num) {
   return num * 2;
@@ -70,7 +70,7 @@ obj.map(function(num) {
 
 

正确的做法,使用一个数组来代替:

-
var numbers = [1, 4, 9];
+
var numbers = [1, 4, 9];
 
 numbers.map(function(num) {
   return num * 2;
@@ -83,7 +83,7 @@ numbers.map(function(num) {
 
 

当您在创建类时,可能会存在某个属性和某个方法的名称相同,当您在调用该函数时,编译器会认为该函数不存在.

-
var Dog = function () {
+
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
 
 

正确的做法是使用不同的变量名.

-
var Dog = function () {
+
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' }<
 
 

使用后者时将会抛出错误:

-
const sixteen = 2(3 + 5);
+
const sixteen = 2(3 + 5);
 alert('2 x (3 + 5) is ' + String(sixteen));
 //Uncaught TypeError: 2 is not a function

您可以添加乘法运算符 * 来改正代码:

-
const sixteen = 2 * (3 + 5);
+
const sixteen = 2 * (3 + 5);
 alert('2 x (3 + 5) is ' + String(sixteen));
 //2 x (3 + 5) is 16
@@ -140,7 +140,7 @@ alert('2 x (3 + 5) is ' + String(sixteen));

以下为一个示例模块 (helpers.js)

-
let helpers = function () { };
+
let helpers = function () { };
 
 helpers.groupBy = function (objectArray, property) {
   return objectArray.reduce(function (acc, obj) {
@@ -158,7 +158,7 @@ export default helpers;

在 App.js中正确导入该模块:

-
import helpers from './helpers'
+
import helpers from './helpers'

相关

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

错误信息

-
ReferenceError: "x" is not defined
+
ReferenceError: "x" is not defined
 

错误类型

@@ -26,19 +26,19 @@ translation_of: Web/JavaScript/Reference/Errors/Not_defined

变量没有被声明

-
foo.substring(1); // ReferenceError: foo is not defined
+
foo.substring(1); // ReferenceError: foo is not defined
 

“foo” 变量没有在任何地方被声明。它需要是某种字符串,这样 {{jsxref("String.prototype.substring()")}} 方法才可以正常工作。

-
var foo = 'bar';
+
var foo = 'bar';
 foo.substring(1); // "ar"

错误的作用域

变量必须是在它当前的执行环境中可用的。在一个函数(function)中定义的变量不能从这个函数外部的任何地方访问,因为这个变量的作用域仅在这个函数的内部。

-
function numbers () {
+
function numbers () {
   var num1 = 2,
       num2 = 3;
   return num1 + num2;
@@ -48,7 +48,7 @@ console.log(num1); // ReferenceError num1 is not defined.

然而,一个函数可用使用在它所被定义的作用域中的所有变量。换句话说,当一个函数被定义在全局作用域的时候,它可以访问所有在全局作用域中定义的变量。

-
var num1 = 2,
+
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
 
 

arguments对象是所有(非箭头)函数中都可用的局部变量。你可以使用arguments对象在函数中引用函数的参数。此对象包含传递给函数的每个参数,第一个参数在索引0处。例如,如果一个函数传递了三个参数,你可以以如下方式引用他们:

-
arguments[0]
+
arguments[0]
 arguments[1]
 arguments[2]
 

参数也可以被设置:

-
arguments[1] = 'new value';
+
arguments[1] = 'new value';

arguments对象不是一个 {{jsxref("Array")}} 。它类似于Array,但除了length属性和索引元素之外没有任何Array属性。例如,它没有 pop 方法。但是它可以被转换为一个真正的Array

-
var args = Array.prototype.slice.call(arguments);
+
var args = Array.prototype.slice.call(arguments);
 var args = [].slice.call(arguments);
 
 // ES2015
@@ -57,7 +57,7 @@ const args = [...arguments];
 

对参数使用slice会阻止某些JavaScript引擎中的优化 (比如 V8 - 更多信息)。如果你关心性能,尝试通过遍历arguments对象来构造一个新的数组。另一种方法是使用被忽视的Array构造函数作为一个函数:

-
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
+
var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments));
 
@@ -67,7 +67,7 @@ const args = [...arguments];

typeof参数返回 'object'。

-
console.log(typeof arguments);    // 'object'
+
console.log(typeof arguments);    // 'object'
 // arguments 对象只能在函数内使用
 function test(a){
     console.log(a,Object.prototype.toString.call(arguments));
@@ -83,13 +83,13 @@ number
 
 

可以使用索引确定单个参数的类型。

-
console.log(typeof arguments[0]); //this will return the typeof individual arguments.
+
console.log(typeof arguments[0]); //this will return the typeof individual arguments.

对参数使用扩展语法

您还可以使用{{jsxref("Array.from()")}}方法或扩展运算符将参数转换为真实数组:

-
var args = Array.from(arguments);
+
var args = Array.from(arguments);
 var args = [...arguments];

属性

@@ -120,7 +120,7 @@ var args = [...arguments];

遍历参数求和

-
function add() {
+
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

这个例子定义了一个函数来连接字符串。这个函数唯一正式声明了的参数是一个字符串,该参数指定一个字符作为衔接点来连接字符串。该函数定义如下:

-
function myConcat(separator) {
+
function myConcat(separator) {
   var args = Array.prototype.slice.call(arguments, 1);
   return args.join(separator);
 }

你可以传递任意数量的参数到该函数,并使用每个参数作为列表中的项创建列表。

-
// returns "red, orange, blue"
+
// returns "red, orange, blue"
 myConcat(", ", "red", "orange", "blue");
 
 // returns "elephant; giraffe; lion; cheetah"
@@ -156,7 +156,7 @@ myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");

这个例子定义了一个函数通过一个字符串来创建HTML列表。这个函数唯一正式声明了的参数是一个字符。当该参数为 "u" 时,创建一个无序列表 (项目列表);当该参数为 "o" 时,则创建一个有序列表 (编号列表)。该函数定义如下:

-
function list(type) {
+
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");

你可以传递任意数量的参数到该函数,并将每个参数作为一个项添加到指定类型的列表中。例如:

-
var listHTML = list("u", "One", "Two", "Three");
+
var listHTML = list("u", "One", "Two", "Three");
 
 /* listHTML is:
 
@@ -180,7 +180,7 @@ myConcat(". ", "sage", "basil", "oregano", "pepper", "parsley");

arguments对象可以与剩余参数默认参数解构赋值参数结合使用。

-
function foo(...args) {
+
function foo(...args) {
   return args;
 }
 foo(1, 2, 3);  // [1,2,3]
@@ -190,7 +190,7 @@ foo(1, 2, 3);  // [1,2,3]
 
 

当非严格模式中的函数没有包含剩余参数默认参数解构赋值,那么arguments对象中的值跟踪参数的值(反之亦然)。看下面的代码:

-
function func(a) {
+
function func(a) {
   arguments[0] = 99;   // 更新了arguments[0] 同样更新了a
   console.log(a);
 }
@@ -199,7 +199,7 @@ func(10); // 99
 
 

并且

-
function func(a) {
+
function func(a) {
   a = 99;              // 更新了a 同样更新了arguments[0]
   console.log(arguments[0]);
 }
@@ -208,7 +208,7 @@ func(10); // 99
 
 

当非严格模式中的函数包含剩余参数默认参数解构赋值,那么arguments对象中的值不会跟踪参数的值(反之亦然)。相反, arguments反映了调用时提供的参数:

-
function func(a = 55) {
+
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

并且

-
function func(a = 55) {
+
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

并且

-
function func(a = 55) {
+
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
 

基础语法

-
(param1, param2, …, paramN) => { statements }
+
(param1, param2, …, paramN) => { statements }
 (param1, param2, …, paramN) => expression
 //相当于:(param1, param2, …, paramN) =>{ return expression; }
 
@@ -39,7 +39,7 @@ singleParam => { statements }
 

高级语法

-
//加括号的函数体返回对象字面量表达式:
+
//加括号的函数体返回对象字面量表达式:
 params => ({foo: bar})
 
 //支持剩余参数默认参数
@@ -60,7 +60,7 @@ f();  // 6

更短的函数

-
var elements = [
+
var elements = [
   'Hydrogen',
   'Helium',
   'Lithium',
@@ -103,7 +103,7 @@ elements.map(({ "length": lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9]
 
 

This被证明是令人厌烦的面向对象风格的编程。

-
function Person() {
+
function Person() {
   // Person() 构造函数定义 `this`作为它自己的实例.
   this.age = 0;
 
@@ -118,7 +118,7 @@ var p = new Person();

在ECMAScript 3/5中,通过将this值分配给封闭的变量,可以解决this问题。

-
function Person() {
+
function Person() {
   var that = this;
   that.age = 0;
 
@@ -132,7 +132,7 @@ var p = new Person();

箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this。因此,在下面的代码中,传递给setInterval的函数内的this与封闭函数中的this值相同:

-
function Person(){
+
function Person(){
   this.age = 0;
 
   setInterval(() => {
@@ -146,7 +146,7 @@ var p = new Person();

鉴于 this 是词法层面上的,严格模式中与 this 相关的规则都将被忽略。

-
var f = () => { 'use strict'; return this; };
+
var f = () => { 'use strict'; return this; };
 f() === window; // 或者 global

严格模式的其他规则依然不变.

@@ -155,7 +155,7 @@ f() === window; // 或者 global

由于 箭头函数没有自己的this指针,通过 call() 或 apply() 方法调用一个函数时,只能传递参数(不能绑定this---译者注),他们的第一个参数会被忽略。(这种现象对于bind方法同样成立---译者注)

-
var adder = {
+
var adder = {
   base : 1,
 
   add : function(a) {
@@ -180,7 +180,7 @@ console.log(adder.addThruCall(1)); // 仍然输出 2

箭头函数不绑定Arguments 对象。因此,在本示例中,arguments只是引用了封闭作用域内的arguments:

-
var arguments = [1, 2, 3];
+
var arguments = [1, 2, 3];
 var arr = () => arguments[0];
 
 arr(); // 1
@@ -198,7 +198,7 @@ foo(3,2);//6
 
 

在大多数情况下,使用剩余参数是相较使用arguments对象的更好选择。

-
function foo(arg) {
+
function foo(arg) {
   var f = (...args) => args[0];
   return f(arg);
 }
@@ -216,7 +216,7 @@ foo(1,2);  //2
 
 

如上所述,箭头函数表达式对非方法函数是最合适的。让我们看看当我们试着把它们作为方法时发生了什么。

-
'use strict';
+
'use strict';
 var obj = {
   i: 10,
   b: () => console.log(this.i, this),
@@ -232,7 +232,7 @@ obj.c();
 
 

箭头函数没有定义this绑定。另一个涉及{{jsxref("Object.defineProperty()")}}的示例:

-
'use strict';
+
'use strict';
 var obj = {
   a: 10
 };
@@ -252,14 +252,14 @@ obj.b; // undefined   "undefined"   Window {postMessage: ƒ, blur: ƒ, focus: ƒ
 
 

箭头函数不能用作构造器,和 new一起用会抛出错误。

-
var Foo = () => {};
+
var Foo = () => {};
 var foo = new Foo(); // TypeError: Foo is not a constructor

使用prototype属性

箭头函数没有prototype属性。

-
var Foo = () => {};
+
var Foo = () => {};
 console.log(Foo.prototype); // undefined

使用 yield 关键字

@@ -272,7 +272,7 @@ console.log(Foo.prototype); // undefined

在一个简写体中,只需要一个表达式,并附加一个隐式的返回值。在块体中,必须使用明确的return语句。

-
var func = x => x * x;
+
var func = x => x * x;
 // 简写函数 省略return
 
 var func = (x, y) => { return x + y; };
@@ -282,7 +282,7 @@ var func = (x, y) => { return x + y; };
 
 

记住用params => {object:literal}这种简单的语法返回对象字面量是行不通的。

-
var func = () => { foo: 1 };
+
var func = () => { foo: 1 };
 // Calling func() returns undefined!
 
 var func = () => { foo: function() {} };
@@ -292,19 +292,19 @@ var func = () => { foo: function() {} };
 
 

所以,记得用圆括号把对象字面量包起来:

-
var func = () => ({foo: 1});
+
var func = () => ({foo: 1});

换行

箭头函数在参数和箭头之间不能换行。

-
var func = ()
+
var func = ()
            => 1;
 // SyntaxError: expected expression, got '=>'

但是,可以通过在 ‘=>’ 之后换行,或者用 ‘( )’、'{ }'来实现换行,如下:

-
var func = (a, b, c) =>
+
var func = (a, b, c) =>
   1;
 
 var func = (a, b, c) => (
@@ -327,7 +327,7 @@ var func = (
 
 

虽然箭头函数中的箭头不是运算符,但箭头函数具有与常规函数不同的特殊运算符优先级解析规则。

-
let callback;
+
let callback;
 
 callback = callback || function() {}; // ok
 
@@ -338,7 +338,7 @@ callback = callback || (() => {});    // ok

更多示例

-
// 空的箭头函数返回 undefined
+
// 空的箭头函数返回 undefined
 let empty = () => {};
 
 (() => 'foobar')();
@@ -383,7 +383,7 @@ setTimeout( () => {
 
 

箭头函数也可以使用条件(三元)运算符:

-
var simple = a => a > 15 ? 15 : a;
+
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;

箭头函数内定义的变量及其作用域

-
// 常规写法
+
// 常规写法
 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
 

箭头函数也可以使用闭包:

-
// 标准的闭包函数
+
// 标准的闭包函数
 function A(){
       var i=0;
       return function b(){
@@ -446,7 +446,7 @@ var Add = (i=0)=> ()=> (++i);
 

 箭头函数递归

-
var fact = (x) => ( x==0 ?  1 : x*fact(x-1) );
+
var fact = (x) => ( x==0 ?  1 : x*fact(x-1) );
 fact(5);       // 120

规范

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

语法

-
new AggregateError(errors[, message])
+
new AggregateError(errors[, message])

参数

@@ -50,7 +50,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/AggregateError

捕获一个AggregateError

-
Promise.any([
+
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
 
 

创建一个AggregateError

-
try {
+
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
 
 

语法

-
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])
+
var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

参数

@@ -53,7 +53,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/concat

以下代码将两个数组合并为一个新数组:

-
var alpha = ['a', 'b', 'c'];
+
var alpha = ['a', 'b', 'c'];
 var numeric = [1, 2, 3];
 
 alpha.concat(numeric);
@@ -63,7 +63,7 @@ alpha.concat(numeric);
 
 

以下代码将三个数组合并为一个新数组:

-
var num1 = [1, 2, 3],
+
var num1 = [1, 2, 3],
     num2 = [4, 5, 6],
     num3 = [7, 8, 9];
 
@@ -76,7 +76,7 @@ console.log(nums);
 
 

以下代码将三个值连接到数组:

-
var alpha = ['a', 'b', 'c'];
+
var alpha = ['a', 'b', 'c'];
 
 var alphaNumeric = alpha.concat(1, [2, 3]);
 
@@ -87,7 +87,7 @@ console.log(alphaNumeric);
 
 

以下代码合并数组并保留引用:

-
var num1 = [[1]];
+
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
 
 

语法

-
arr.every(callback(element[, index[, array]])[, thisArg])
+
arr.every(callback(element[, index[, array]])[, thisArg])

参数

@@ -68,7 +68,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/every

下例检测数组中的所有元素是否都大于 10。

-
function isBigEnough(element, index, array) {
+
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
 
 

箭头函数为上面的检测过程提供了更简短的语法。

-
[12, 5, 8, 130, 44].every(x => x >= 10); // false
+
[12, 5, 8, 130, 44].every(x => x >= 10); // false
 [12, 54, 18, 130, 44].every(x => x >= 10); // true

兼容旧环境(Polyfill)

在 ECMA-262 第 5 版时,every 被添加进 ECMA-262 标准;因此,在某些实现环境中,它尚未被支持。你可以把下面的代码放到脚本的开头来解决此问题,该代码允许在那些没有原生支持 every 的实现环境中使用它。该算法是 ECMA-262 第 5 版中指定的算法,它假定 Object 和 TypeError 拥有它们的初始值,且 fun.call 等价于 {{jsxref("Function.prototype.call")}}。

-
if (!Array.prototype.every) {
+
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
 
 

语法

-
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
+
var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

参数

@@ -69,7 +69,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/filter

下例使用 filter 创建了一个新数组,该数组的元素由原数组中值大于 10 的元素组成。

-
function isBigEnough(element) {
+
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);
 
 

以下示例使用 filter() 创建具有非零 id 的元素的 json。

-
var arr = [
+
var arr = [
   { id: 15 },
   { id: -1 },
   { id: 0 },
@@ -120,7 +120,7 @@ console.log('Number of Invalid Entries = ', invalidEntries);
 
 

下例使用 filter() 根据搜索条件来过滤数组内容。

-
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
+
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']

ES2015 实现

-
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
+
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']
 
 

filter 被添加到 ECMA-262 标准第 5 版中,因此在某些实现环境中不被支持。可以把下面的代码插入到脚本的开头来解决此问题,该代码允许在那些没有原生支持 filter 的实现环境中使用它。该算法是 ECMA-262 第 5 版中指定的算法,假定 fn.call 等价于 {{jsxref("Function.prototype.call")}} 的初始值,且 {{jsxref("Array.prototype.push")}} 拥有它的初始值。

-
if (!Array.prototype.filter){
+
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
 
 

语法

-
arr.findIndex(callback[, thisArg])
+
arr.findIndex(callback[, thisArg])

参数

@@ -62,7 +62,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/findIndex

以下示例查找数组中素数的元素的索引(如果不存在素数,则返回-1)。

-
function isPrime(element, index, array) {
+
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

Polyfill

-
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
+
// 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
 
 

语法

-
var newArray = arr.flat([depth])
+
var newArray = arr.flat([depth])

参数

@@ -36,7 +36,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/flat

扁平化嵌套数组

-
var arr1 = [1, 2, [3, 4]];
+
var arr1 = [1, 2, [3, 4]];
 arr1.flat();
 // [1, 2, 3, 4]
 
@@ -57,7 +57,7 @@ arr4.flat(Infinity);
 
 

flat() 方法会移除数组中的空项:

-
var arr4 = [1, 2, , 4, 5];
+
var arr4 = [1, 2, , 4, 5];
 arr4.flat();
 // [1, 2, 4, 5]
@@ -65,7 +65,7 @@ arr4.flat();

使用 reduceconcat

-
var arr = [1, 2, [3, 4]];
+
var arr = [1, 2, [3, 4]];
 
 // 展开一层数组
 arr.flat();
@@ -78,7 +78,7 @@ const flattened = arr => [].concat(...arr);

reduce + concat + isArray + recursivity

-
// 使用 reduce、concat 和递归展开无限多层嵌套的数组
+
// 使用 reduce、concat 和递归展开无限多层嵌套的数组
 var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
 
 function flatDeep(arr, d = 1) {
@@ -91,7 +91,7 @@ flatDeep(arr1, Infinity);
 
 

forEach+isArray+push+recursivity

-
// forEach 遍历数组会自动跳过空元素
+
// forEach 遍历数组会自动跳过空元素
 const eachFlat = (arr = [], depth = 1) => {
   const result = []; // 缓存递归结果
   // 开始递归
@@ -131,7 +131,7 @@ const forFlat = (arr = [], depth = 1) => {
 
 

使用堆栈stack

-
// 无递归数组扁平化,使用堆栈
+
// 无递归数组扁平化,使用堆栈
 // 注意:深度的控制比较低效,因为需要检查每一个值的深度
 // 也可能在 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]
-
// 递归版本的反嵌套
+
// 递归版本的反嵌套
 function flatten(array) {
   var flattend = [];
   (function flat(array) {
@@ -167,7 +167,7 @@ function flatten(array) {
 
 

Use Generator function

-
function* flatten(array) {
+
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
 
 

语法

-
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
+
var new_array = arr.flatMap(function callback(currentValue[, index[, array]]) {
     // return element for new_array
 }[, thisArg])
@@ -54,7 +54,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/flatMap

map() 与 flatMap()

-
var arr1 = [1, 2, 3, 4];
+
var arr1 = [1, 2, 3, 4];
 
 arr1.map(x => [x * 2]);
 // [[2], [4], [6], [8]]
@@ -70,7 +70,7 @@ arr1.flatMap(x => [[x * 2]]);
 
 

所以,为了更好的展示 flatMap 的作用,下面我们将包含几句话的数组拆分成单个词组成的新数组。

-
let arr1 = ["it's Sunny in", "", "California"];
+
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(" "));
 
 

flatMap 能用于在map期间增删项目(也就是修改items的数量)。换句话说,它允许你遍历很多项使之成为另一些项(靠分别把它们放进去来处理),而不是总是一对一。 从这个意义上讲,它的作用类似于 filter的对立面。只需返回一个1项元素数组以保留该项,返回一个多元素数组以添加项,或返回一个0项元素数组以删除该项。

-
// Let's say we want to remove all the negative numbers and split the odd numbers into an even number and a 1
+
// 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) =>
 
 

reduce() 与 concat()

-
var arr = [1, 2, 3, 4];
+
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
 
 

语法

-
Array.from(arrayLike[, mapFn[, thisArg]])
+
Array.from(arrayLike[, mapFn[, thisArg]])
 

参数

@@ -59,18 +59,18 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/from

String 生成数组

-
Array.from('foo');
+
Array.from('foo');
 // [ "f", "o", "o" ]

Set 生成数组

-
const set = new Set(['foo', 'bar', 'baz', 'foo']);
+
const set = new Set(['foo', 'bar', 'baz', 'foo']);
 Array.from(set);
 // [ "foo", "bar", "baz" ]

Map 生成数组

-
const map = new Map([[1, 2], [2, 4], [4, 8]]);
+
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());
 
 

从类数组对象(arguments)生成数组

-
function f() {
+
function f() {
   return Array.from(arguments);
 }
 
@@ -94,7 +94,7 @@ f(1, 2, 3);
 
 

Array.from 中使用箭头函数

-
// Using an arrow function as the map function to
+
// 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);
 
 

序列生成器(指定范围)

-
// Sequence generator function (commonly referred to as "range", e.g. Clojure, PHP etc)
+
// 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
 
 

数组去重合并

-
function combine(){
+
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]

ECMA-262 第六版标准中添加了 Array.from 。有些实现中可能尚未包括在其中。你可以通过在脚本前添加如下内容作为替代方法,以使用未原生支持的 Array.from 方法。该算法按照 ECMA-262 第六版中的规范实现,并假定 ObjectTypeError 有其本身的值, callback.call 对应 {{jsxref("Function.prototype.call")}} 。此外,鉴于无法使用 Polyfill 实现真正的的迭代器,该实现不支持规范中定义的泛型可迭代元素。

-
// Production steps of ECMA-262, Edition 6, 22.1.2.1
+
// 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
 
 

语法

-
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
+
var new_array = arr.map(function callback(currentValue[, index[, array]]) {
  // Return element for new_array 
 }[, thisArg])
@@ -68,7 +68,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/map

下面的代码创建了一个新数组,值为原数组中对应数字的平方根。

-
var numbers = [1, 4, 9];
+
var numbers = [1, 4, 9];
 var roots = numbers.map(Math.sqrt);
 // roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]
@@ -76,7 +76,7 @@ var roots = numbers.map(Math.sqrt);

以下代码使用一个包含对象的数组来重新创建一个格式化后的数组。

-
var kvArray = [{key: 1, value: 10},
+
var kvArray = [{key: 1, value: 10},
                {key: 2, value: 20},
                {key: 3, value: 30}];
 
@@ -98,7 +98,7 @@ var reformattedArray = kvArray.map(function(obj) {
 
 

下面的代码表示了当函数需要一个参数时map的工作方式。当map循环遍历原始数组时,这个参数会自动被分配成数组中对应的每个元素。

-
var numbers = [1, 4, 9];
+
var numbers = [1, 4, 9];
 var doubles = numbers.map(function(num) {
   return num * 2;
 });
@@ -110,7 +110,7 @@ var doubles = numbers.map(function(num) {
 
 

下面的例子演示如何在一个 {{jsxref("String")}}  上使用 map 方法获取字符串中每个字符所对应的 ASCII 码组成的数组:

-
var map = Array.prototype.map
+
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) {
 
 

下面代码展示了如何去遍历用 querySelectorAll 得到的动态对象集合。在这里,我们获得了文档里所有选中的选项,并将其打印:

-
var elems = document.querySelectorAll('select option:checked');
+
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) {
 
 

考虑下例:

-
["1", "2", "3"].map(parseInt);
+
["1", "2", "3"].map(parseInt);

我们期望输出 [1, 2, 3], 而实际结果是 [1, NaN, NaN].

@@ -149,14 +149,14 @@ var values = Array.prototype.map.call(elems, function(obj) {

第三个参数被parseInt忽视了, but not the second one, 但不是第二个。因此可能出现混淆。下面是迭代步骤的简明示例:

-
// parseInt(string, radix) -> map(parseInt(value, index))
+
// 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

下面让我们来讨论解决方案:

-
function returnInt(element) {
+
function returnInt(element) {
   return parseInt(element, 10);
 }
 
@@ -176,7 +176,7 @@ var values = Array.prototype.map.call(elems, function(obj) {
 
 

一个map方法调用 parseInt 作为一个参数的等效输出运行如下:

-
var xs = ['10', '10', '10'];
+
var xs = ['10', '10', '10'];
 
 xs = xs.map(parseInt);
 
@@ -187,7 +187,7 @@ console.log(xs);  // 输出结果为(3) [10, NaN, 2]
 
 

当返回undefined 或没有返回任何内容时:

-
var numbers = [1, 2, 3, 4];
+
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) {
 
 

map 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 map 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 callback.call evaluates to the original value of {{jsxref("Function.prototype.call")}}.

-
// Production steps of ECMA-262, Edition 5, 15.4.4.19
+
// 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
 
 

语法

-
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
+
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])

参数

@@ -89,7 +89,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/Reduce

提供初始值通常更安全,正如下面的例子,如果没有提供initialValue,则可能有四种输出:

-
var maxCallback = ( acc, cur ) => Math.max( acc.x, cur.x );
+
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 );
 
 

假如运行下段reduce()代码:

-
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
+
[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array){
   return accumulator + currentValue;
 });
 
@@ -172,11 +172,11 @@ var maxCallback2 = ( max, cur ) => Math.max( max, cur );

你还可以使用{{jsxref("Functions/Arrow_functions", "箭头函数","",1)}}来代替完整的函数。 下面的代码将产生与上面的代码相同的输出:

-
[0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr );
+
[0, 1, 2, 3, 4].reduce((prev, curr) => prev + curr );

如果你打算提供一个初始值作为reduce()方法的第二个参数,以下是运行过程及结果:

-
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
+
[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => {
     return accumulator + currentValue
 }, 10)
 
@@ -332,14 +332,14 @@ var maxCallback2 = ( max, cur ) => Math.max( max, cur );

数组里所有值的和

-
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
+
var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
   return accumulator + currentValue;
 }, 0);
 // 和为 6

你也可以写成箭头函数的形式:

-
var total = [ 0, 1, 2, 3 ].reduce(
+
var total = [ 0, 1, 2, 3 ].reduce(
   ( acc, cur ) => acc + cur,
   0
 );
@@ -348,7 +348,7 @@ var maxCallback2 = ( max, cur ) => Math.max( max, cur );

要累加对象数组中包含的值,必须提供初始值,以便各个item正确通过你的函数。

-
var initialValue = 0;
+
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

你也可以写成箭头函数的形式:

-
var initialValue = 0;
+
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
 
 

将二维数组转化为一维

-
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+
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
 
 

你也可以写成箭头函数的形式:

-
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
+
var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  ( acc, cur ) => acc.concat(cur),
  []
 );
@@ -388,7 +388,7 @@ console.log(sum) // logs 6
 
 

计算数组中每个元素出现的次数

-
var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
+
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) {
 
 

按属性对object分类

-
var people = [
+
var people = [
   { name: 'Alice', age: 21 },
   { name: 'Max', age: 20 },
   { name: 'Jane', age: 20 }
@@ -434,7 +434,7 @@ var groupedPeople = groupBy(people, 'age');
 
 

使用扩展运算符和initialValue绑定包含在对象数组中的数组

-
// friends - 对象数组
+
// friends - 对象数组
 // where object field "books" - list of favorite books
 var friends = [{
   name: 'Anna',
@@ -469,7 +469,7 @@ var allbooks = friends.reduce(function(prev, curr) {
 

注意: 如果你正在使用一个可以兼容{{jsxref("Set")}} 和 {{jsxref("Array.from()")}} 的环境, 你可以使用let orderedArray = Array.from(new Set(myArray)); 来获得一个相同元素被移除的数组。

-
let myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd']
+
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)
-
let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
+
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]

按顺序运行Promise

-
/**
+
/**
  * Runs promises from array of functions that can return promises
  * in chained manner
  *
@@ -537,7 +537,7 @@ runPromiseInSequence(promiseArr, 10)
 
 

功能型函数管道

-
// Building-blocks to use for composition
+
// 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
 
 

使用 reduce实现map

-
if (!Array.prototype.mapUsingReduce) {
+
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
 
 

Polyfill

-
// Production steps of ECMA-262, Edition 5, 15.4.4.21
+
// 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
 
 

语法

-
arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])
+
arr.reduceRight(callback(accumulator, currentValue[, index[, array]])[, initialValue])

参数

@@ -55,7 +55,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

可以像下面这样调用 reduceRight 的回调函数 callback

-
array.reduceRight(function(accumulator, currentValue, index, array) {
+
array.reduceRight(function(accumulator, currentValue, index, array) {
   // ...
 });
@@ -111,7 +111,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

该函数的完整执行过程见下例:

-
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
+
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
     return previousValue + currentValue;
 });
 
@@ -169,7 +169,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

如果提供了一个 initialValue 参数,则结果如下:

-
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
+
[0, 1, 2, 3, 4].reduceRight(function(previousValue, currentValue, index, array) {
     return previousValue + currentValue;
 }, 10);
 
@@ -235,14 +235,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/ReduceRight

求一个数组中所有值的和

-
var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
+
var sum = [0, 1, 2, 3].reduceRight(function(a, b) {
   return a + b;
 });
 // sum is 6

扁平化(flatten)一个二维数组

-
var flattened = [[0, 1], [2, 3], [4, 5]].reduceRight(function(a, b) {
+
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
 
 

运行一个带有回调每个函数将其结果传给下一个的异步函数列表

-
const waterfall = (...functions) => (callback, ...args) =>
+
const waterfall = (...functions) => (callback, ...args) =>
   functions.reduceRight(
     (composition, fn) => (...results) => fn(composition, ...results),
     callback
@@ -293,7 +293,7 @@ const computation2 = (input, callback) => {
 
 

展示 reducereduceRight 之间的区别

-
var a = ['1', '2', '3', '4', '5'];
+
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"

组合函数的概念简单,它只是简单地结合了多个函数。它是一个从右向左流动的函数,用上一个函数的输出调用每个函数。

-
/**
+
/**
  * 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

reduceRight 被添加到 ECMA-262 标准第 5 版,因此它在某些实现环境中可能不被支持。把下面的代码添加到脚本开头可以解决此问题,从而允许在那些没有原生支持 reduceRight 的实现环境中使用它。

-
// Production steps of ECMA-262, Edition 5, 15.4.4.22
+
// 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
 
 

语法

-
arr.slice([begin[, end]])
+
arr.slice([begin[, end]])

参数

@@ -63,7 +63,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/slice

返回现有数组的一部分

-
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
+
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);
 
 

在下例中, slicemyCar 中创建了一个新数组newCar。两个数组都包含了一个 myHonda 对象的引用。当 myHondacolor 属性改变为 purple,则两个数组中的对应元素都会随之改变。

-
// 使用 slice 方法从 myCar 中创建一个 newCar。
+
// 使用 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);
 
 

上述代码输出:

-
 myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
+
 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
 
 

slice 方法可以用来将一个类数组(Array-like)对象/集合转换成一个新数组。你只需将该方法绑定到这个对象上。 一个函数中的  {{jsxref("Functions/arguments", "arguments")}} 就是一个类数组对象的例子。

-
function list() {
+
function list() {
   return Array.prototype.slice.call(arguments);
 }
 
@@ -123,7 +123,7 @@ var list1 = list(1, 2, 3); // [1, 2, 3]
 
 

除了使用 Array.prototype.slice.call(arguments),你也可以简单的使用 [].slice.call(arguments) 来代替。另外,你可以使用 bind 来简化该过程。

-
var unboundSlice = Array.prototype.slice;
+
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]
 
 

根据规范,使用 Array.prototype.slice 转换宿主对象(如 DOM 对象)时,不必遵循 Mozilla 的默认行为,即可以转化任何符合条件的伪数组宿主对象为数组,IE < 9 没有遵循,而 IE9 + 遵循这个行为,但是稍加改造可以使其在跨浏览器使用时更可靠。只要其他现代浏览器继续支持该行为,目前 IE 9+、FireFox、Chrome、Safari 以及 Opera 都支持,开发者在使用下面代码时遍历 DOM 时就不会被该方法的字面意义误导,即 IE < 9 不能转化 DOM Collections。开发者可以安全地根据语义知道该方法的实际上的标准行为。(下面的代码还修正了 IE 中 slice() 方法第二个参数不允许为显式的 {{jsxref("Global_Objects/null", "null")}}/{{jsxref("Global_Objects/undefined", "undefined")}} 值的问题,其他现代浏览器,包括 IE9+ 都允许)。

-
/**
+
/**
  * 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
 
 

语法

-
arr.values()
+
arr.values()

返回值

@@ -30,7 +30,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Array/values

使用 for...of 循环进行迭代

-
let arr = ['w', 'y', 'k', 'o', 'p'];
+
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) {
 
 

Array.prototype.values 是 Array.prototype[Symbol.iterator] 的默认实现。

-
Array.prototype.values === Array.prototype[Symbol.iterator]  // true 
+
Array.prototype.values === Array.prototype[Symbol.iterator]  // true 

使用 .next() 迭代

-
var arr = ['a', 'b', 'c', 'd', 'e'];
+
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

例子:

-
var arr = ['a', 'b', 'c', 'd', 'e'];
+
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);
 
 

: 数组迭代器中存储的是原数组的地址,而不是数组元素值。

-
var arr = ['a', 'b', 'c', 'd', 'e'];
+
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
 
 

语法

-
new ArrayBuffer(length)
+
new ArrayBuffer(length)
 

参数

@@ -104,7 +104,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/ArrayBuffer

下面的例子创建了一个 8 字节的缓冲区,并使用一个 {{jsxref("Global_Objects/Int32Array", "Int32Array")}} 来引用它:

-
var buffer = new ArrayBuffer(8);
+
var buffer = new ArrayBuffer(8);
 var view   = new Int32Array(buffer);
 
@@ -143,11 +143,11 @@ var view = new Int32Array(buffer);

从 ECMAScript 2015 开始,ArrayBuffer 对象需要用 {{jsxref("Operators/new", "new")}} 运算符创建。如果调用构造函数时没有使用 new,将会抛出 {{jsxref("TypeError")}}  异常。

-
var dv = ArrayBuffer(10);
+
var dv = ArrayBuffer(10);
 // TypeError: calling a builtin ArrayBuffer constructor
 // without new is forbidden
-
var dv = new ArrayBuffer(10);
+
var dv = new ArrayBuffer(10);

相关链接

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

使用 Atomics

-
const sab = new SharedArrayBuffer(1024);
+
const sab = new SharedArrayBuffer(1024);
 const ta = new Uint8Array(sab);
 
 ta[0];
@@ -101,19 +101,19 @@ Atomics.load(ta, 0); // 4
 
 

给定一个共享的 Int32Array

-
const sab = new SharedArrayBuffer(1024);
+
const sab = new SharedArrayBuffer(1024);
 const int32 = new Int32Array(sab);
 

读取线程正在休眠并位置0上等待。只要该位置应为0,它就不会继续。但是,一旦写入线程存储了新值,写入线程将通知它并返回新值(123)。

-
Atomics.wait(int32, 0, 0);
+
Atomics.wait(int32, 0, 0);
 console.log(int32[0]); // 123
 

写入线程存储一个新值并再写入完成时通知等待线程:

-
console.log(int32[0]); // 0;
+
console.log(int32[0]); // 0;
 Atomics.store(int32, 0, 123);
 Atomics.notify(int32, 0, 1);
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

语法

-
Atomics.notify(typedArray, index, count)
+
Atomics.notify(typedArray, index, count)
 

参数

@@ -47,18 +47,18 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Atomics/notify

分配一个共享的 Int32Array

-
var sab = new SharedArrayBuffer(1024);
+
var sab = new SharedArrayBuffer(1024);
 var int32 = new Int32Array(sab);
 

一个读线程会进入休眠并监视索引0处的值(默认为0)。只要索引0处的值不为0,读进程就会唤醒。但是,一旦写进程存储了一个新的值,写进程就会产生一个提醒并返回写入后的新值(123)。(这里示例有问题或者说对初学者不友好,如果直接在浏览器控制台运行下面代码会报错,因为我们不能尝试睡眠主线程,可以见 重学js —— 结构化数据之Atomics对象,同时我在 codepen 写了一个示例:Atomics.wait使用示例

-
Atomics.wait(int32, 0, 0);
+
Atomics.wait(int32, 0, 0);
 console.log(int32[0]); // 123

写进程写入一个新值并告知等待进程已经写入成功了:

-
console.log(int32[0]); // 0;
+
console.log(int32[0]); // 0;
 Atomics.store(int32, 0, 123);
 Atomics.notify(int32, 0, 1);
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

不同的方法去创建一个 BigInt64Array

-
// From a length
+
// 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
 
 

其值不是{{jsxref("undefined")}}或{{jsxref("null")}}的任何对象(包括其值为false的布尔对象)在传递给条件语句时都将计算为true。 例如,以下{{jsxref("Statements/if...else", "if")}}语句中的条件评估为true

-
var x = new Boolean(false);
+
var x = new Boolean(false);
 if (x) {
   // 这里的代码会被执行
 }
@@ -27,7 +27,7 @@ if (x) {
 
 

基本类型的布尔值不受此规则影响。例如下面的 {{jsxref("Statements/if...else", "if")}} 语句的条件为假:

-
var x = false;
+
var x = false;
 if (x) {
   // 这里的代码不会执行
 }
@@ -35,14 +35,14 @@ if (x) {
 
 

不要用创建 Boolean 对象的方式将一个非布尔值转化成布尔值,直接将 Boolean 当做转换函数来使用即可,或者使用双重非(!!)运算符

-
var x = Boolean(expression);     // 推荐
+
var x = Boolean(expression);     // 推荐
 var x = !!(expression);          // 推荐
 var x = new Boolean(expression); // 不太好
 

对于任何对象,即使是值为 falseBoolean 对象,当将其传给 Boolean 函数时,生成的 Boolean 对象的值都是 true

-
var myFalse = new Boolean(false);   // true
+
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
 
 

创建值为 false 的 Boolean 对象

-
var bNoParam = new Boolean();
+
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);
 
 

创建值为 true 的  Boolean 对象

-
var btrue = new Boolean(true);
+
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
 
 

语法

-
new Date();
+
new Date();
 new Date(value);
 new Date(dateString);
 new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]]);
@@ -147,7 +147,7 @@ new Date(year, monthIndex [, day [, hours<

注意: 由于浏览器差异和不一致性,强烈建议不要使用Date构造函数(和Date.parse,它们是等效的)解析日期字符串。

-
var today = new Date();
+
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);
 
 

为了创建和获取 0 到 99 之间的年份,应使用 {{jsxref("Date.prototype.setFullYear()")}} 和 {{jsxref("Date.prototype.getFullYear()")}} 方法。

-
var date = new Date(98, 1); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT)
+
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)
 
 

由于不同日期、月份、年份长度的不同(日期长度不同来自夏令时的切换),使用大于秒、分钟、小时的单位表示经过的时间会遇到很多问题,在使用前需要经过详尽的调研。

-
// 使用 Date 对象
+
// 使用 Date 对象
 var start = Date.now();
 
 // 调用一个消耗一定时间的方法:
@@ -180,7 +180,7 @@ doSomethingForALongTime();
 var end = Date.now();
 var elapsed = end - start; // 以毫秒计的运行时长
-
// 使用内建的创建方法
+
// 使用内建的创建方法
 var start = new Date();
 
 // 调用一个消耗一定时间的方法:
@@ -188,7 +188,7 @@ doSomethingForALongTime();
 var end = new Date();
 var elapsed = end.getTime() - start.getTime(); // 运行时间的毫秒值
-
// to test a function and get back its return
+
// 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);
 
 

获取自 Unix 起始时间以来经过的秒数

-
var seconds = Math.floor(Date.now() / 1000);
+
var seconds = Math.floor(Date.now() / 1000);

注意此处需要返回一个整数 (仅做除法得到的不是整数),并且需要返回实际已经经过的秒数(所以这里使用了{{jsxref("Math.floor()")}}而不是{{jsxref("Math.round()")}}).

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

语法

-
encodeURIComponent(str);
+
encodeURIComponent(str);

参数

@@ -32,7 +32,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/encodeURIComponent

encodeURIComponent 转义除了如下所示外的所有字符:

-
不转义的字符:
+
不转义的字符:
     A-Z a-z 0-9 - _ . ! ~ * ' ( )

encodeURIComponent()encodeURI 有以下几个不同点:

@@ -54,7 +54,7 @@ console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (the space gets encode

注意,如果试图编码一个非高-低位完整的代理字符,将会抛出一个 {{jsxref("URIError")}} 错误,例如:

-
// 高低位完整
+
// 高低位完整
 alert(encodeURIComponent('\uD800\uDFFF'));
 
 // 只有高位,将抛出"URIError: malformed URI sequence"
@@ -69,7 +69,7 @@ alert(encodeURIComponent('\uDFFF')); 

为了更严格的遵循 {{rfc("3986")}}(它保留 !, ', (, ), 和 *),即使这些字符并没有正式划定 URI 的用途,下面这种方式是比较安全的:

-
function fixedEncodeURIComponent (str) {
+
function fixedEncodeURIComponent (str) {
   return encodeURIComponent(str).replace(/[!'()*]/g, function(c) {
     return '%' + c.charCodeAt(0).toString(16).toUpperCase();
   });
@@ -79,7 +79,7 @@ alert(encodeURIComponent('\uDFFF')); 

下面这个例子提供了 UTF-8 下 {{HTTPHeader("Content-Disposition")}} 和 {{HTTPHeader("Link")}} 的服务器响应头信息的参数(例如 UTF-8 文件名):

-
var fileName = 'my file(2).txt';
+
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
 
 

你在回调中创建了如下的 registry:

-
const registry = new FinalizationRegistry(heldValue => {
+
const registry = new FinalizationRegistry(heldValue => {
   // ....
 });
 

然后,你可以通过调用`register`方法,注册任何你想要清理回调的对象,传入该对象和*所含的值*。

-
registry.register(theObject, "some value");
+
registry.register(theObject, "some value");
 

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).

@@ -39,14 +39,14 @@ translation_of: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry

It's common to use the object itself as the unregister token, which is just fine:

-
registry.register(theObject, "some value", theObject);
+
registry.register(theObject, "some value", theObject);
 // ...some time later, if you don't care about `theObject` anymore...
 registry.unregister(theObject);
 

It doesn't have to be the same object, though; it can be a different one:

-
registry.register(theObject, "some value", tokenObject);
+
registry.register(theObject, "some value", tokenObject);
 // ...some time later, if you don't care about `theObject` anymore...
 registry.unregister(tokenObject);
 
@@ -108,7 +108,7 @@ registry.unregister(tokenObject);

You create the registry passing in the callback:

-
const registry = new FinalizationRegistry(heldValue => {
+
const registry = new FinalizationRegistry(heldValue => {
   // ....
 });
 
@@ -117,7 +117,7 @@ registry.unregister(tokenObject);

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:

-
registry.register(theObject, "some value");
+
registry.register(theObject, "some value");

Specifications

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

语法

-
func.apply(thisArg, [argsArray])
+
func.apply(thisArg, [argsArray])

参数

@@ -58,7 +58,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Function/apply

apply正派上用场!

-
var array = ['a', 'b'];
+
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]
 
 

下面是示例,我们将用Math.max/Math.min求得数组中的最大/小值。

-
/* 找出数组中最大/小的数字 */
+
/* 找出数组中最大/小的数字 */
 var numbers = [5, 6, 2, 3, 7];
 
 /* 使用Math.min/Math.max以及apply 函数时的代码 */
@@ -91,7 +91,7 @@ for (var i = 0; i < numbers.length; i++) {
 
 

如果你的参数数组可能非常大,那么推荐使用下面这种混合策略:将数组切块后循环传入目标方法:

-
function minOfArray(arr) {
+
function minOfArray(arr) {
   var min = Infinity;
   var QUANTUM = 32768;
 
@@ -110,7 +110,7 @@ var min = minOfArray([5, 6, 2, 3, 7]);
 
 

你可以使用apply来链接一个对象构造器,类似于Java。在接下来的例子中我们会创建一个全局Function 对象的construct方法 ,来使你能够在构造器中使用一个类数组对象而非参数列表。

-
Function.prototype.construct = function (aArgs) {
+
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]);
 
 

Using {{jsxref("Object/__proto__", "Object.__proto__")}}:

-
Function.prototype.construct = function (aArgs) {
+
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]);
 
 

使用闭包:

-
Function.prototype.construct = function(aArgs) {
+
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]);
 
 

使用 Function 构造器:

-
Function.prototype.construct = function (aArgs) {
+
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]);
 
 

使用示例:

-
function MyConstructor (arguments) {
+
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
 
 

语法

-
function.bind(thisArg[, arg1[, arg2[, ...]]])
+
function.bind(thisArg[, arg1[, arg2[, ...]]])

参数

@@ -63,7 +63,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Function/bind

bind() 最简单的用法是创建一个函数,不论怎么调用,这个函数都有同样的 this 值。JavaScript新手经常犯的一个错误是将一个方法从对象中拿出来,然后再调用,期望方法中的 this 是原来的对象(比如在回调中传入这个方法)。如果不做特殊处理的话,一般会丢失原来的对象。基于这个函数,用原始的对象创建一个绑定函数,巧妙地解决了这个问题:

-
this.x = 9;    // 在浏览器中,this 指向全局的 "window" 对象
+
this.x = 9;    // 在浏览器中,this 指向全局的 "window" 对象
 var module = {
   x: 81,
   getX: function() { return this.x; }
@@ -85,7 +85,7 @@ boundGetX(); // 81
 
 

bind() 的另一个最简单的用法是使一个函数拥有预设的初始参数。只要将这些参数(如果有的话)作为 bind() 的参数写在 this 后面。当绑定函数被调用时,这些参数会被插入到目标函数的参数列表的开始位置,传递给绑定函数的参数会跟在它们后面。

-
function list() {
+
function list() {
   return Array.prototype.slice.call(arguments);
 }
 
@@ -120,7 +120,7 @@ var result3 = addThirtySeven(5, 10);
 
 

在默认情况下,使用 {{ domxref("window.setTimeout()") }} 时,this 关键字会指向 {{ domxref("window") }} (或 global)对象。当类的方法中需要 this 指向类的实例时,你可能需要显式地把 this 绑定到回调函数,就不会丢失该实例的引用。

-
function LateBloomer() {
+
function LateBloomer() {
   this.petalCount = Math.ceil(Math.random() * 12) + 1;
 }
 
@@ -145,7 +145,7 @@ flower.bloom();  // 一秒钟后, 调用 'declare' 方法

绑定函数自动适应于使用 {{jsxref("Operators/new", "new")}} 操作符去构造一个由目标函数创建的新实例。当一个绑定函数是用来构建一个值的,原来提供的 this 就会被忽略。不过提供的参数列表仍然会插入到构造函数调用时的参数列表之前。

-
function Point(x, y) {
+
function Point(x, y) {
   this.x = x;
   this.y = y;
 }
@@ -178,7 +178,7 @@ new YAxisPoint(17, 42) instanceof Point; // true

请注意,你不需要做特别的处理就可以创建一个和 {{jsxref("Operators/new", "new")}} 操作符一起使用的绑定函数。也就是说,你不需要做特别处理就可以创建一个可以被直接调用的绑定函数,即使你更希望绑定函数是用 {{jsxref("Operators/new", "new")}} 操作符来调用。

-
// ...接着上面的代码继续的话,
+
// ...接着上面的代码继续的话,
 // 这个例子可以直接在你的 JavaScript 控制台运行
 
 // 仍然能作为一个普通函数来调用
@@ -196,7 +196,7 @@ emptyObj.x + ',' + emptyObj.y;   //  '0,13'
 
 

你可以用 {{jsxref("Array.prototype.slice")}} 来将一个类似于数组的对象(array-like object)转换成一个真正的数组,就拿它来举例子吧。你可以简单地这样写:

-
var slice = Array.prototype.slice;
+
var slice = Array.prototype.slice;
 
 // ...
 
@@ -204,7 +204,7 @@ slice.apply(arguments);

bind()可以使这个过程变得简单。在下面这段代码里面,slice 是 {{jsxref("Function.prototype")}} 的 {{jsxref("Function.prototype.apply()", "apply()")}} 方法的绑定函数,并且将 {{jsxref("Array.prototype")}} 的 {{jsxref("Array.prototype.slice()", "slice()")}} 方法作为 this 的值。这意味着我们压根儿用不着上面那个 apply()调用了。

-
// 与前一段代码的 "slice" 效果相同
+
// 与前一段代码的 "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
 
 

语法

-
globalThis
+
globalThis

描述

@@ -46,7 +46,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/globalThis

globalThis 之前,获取某个全局对象的唯一方式就是 Function('return this')(),但是这在某些情况下会违反 CSP 规则,所以,es6-shim 使用了类似如下的方式:

-
var getGlobal = function () {
+
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') {
 
 

但是有了 globalThis 之后,只需要:

-
if (typeof globalThis.setTimeout !== 'function') {
+
if (typeof globalThis.setTimeout !== 'function') {
   //  此环境中没有 setTimeout 方法!
 }
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

示例

-
console.log(Infinity          ); /* Infinity */
+
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
 
 

很简单,就是需要给{{jsxref("Locale/Locale", "Intl.Locale")}} 构造函数传入一个 locale 标识字符串作为参数:

-
let us = new Intl.Locale('zh-Hans-CN');
+
let us = new Intl.Locale('zh-Hans-CN');

使用配置实例化

构造函数支持传入 object 作为配置,object 中可包含多个配置属性。例如,设置 hourCycle 属性,用于设置您所需要的小时周期类型:

-
let zh12hour = new Intl.Locale("zh-Hans-CN", {hourCycle: "h12"});
+
let zh12hour = new Intl.Locale("zh-Hans-CN", {hourCycle: "h12"});
 console.log(zh12hour.hourCycle); // Prints "h12"

规范

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

句法

-
new Intl.RelativeTimeFormat([locales[, options]])
+
new Intl.RelativeTimeFormat([locales[, options]])
 

参数

@@ -84,7 +84,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat

以下示例显示如何使用英语创建相对时间格式化程序。

-
//在语言环境中创建相对时间格式化程序
+
//在语言环境中创建相对时间格式化程序
 //显式传入默认值。
 const rtf = new Intl.RelativeTimeFormat("en",{
     localeMatcher: "bestfit",//其他值:"lookup"
@@ -104,7 +104,7 @@ rtf.format(1,"day");
 
 

如果numeric:auto选项被传递,它将生成字符串yesterdaytomorrow代替1 day agoin 1 day。这允许不必总是在输出中使用数值。

-
//在语言环境中创建相对时间格式化程序
+
//在语言环境中创建相对时间格式化程序
 //使用数字:传入"auto"选项值。
 const rtf = new Intl.RelativeTimeFormat("en",{numeric: "auto"});
 
@@ -121,7 +121,7 @@ rtf.format(1,"day");
 
 

以下示例显示如何创建返回格式化部件的相对时间格式器

-
const rtf = new Intl.RelativeTimeFormat("en",{numeric: "auto"});
+
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
 
 

语法

-
JSON.stringify(value[, replacer [, space]])
+
JSON.stringify(value[, replacer [, space]])
 

参数

@@ -64,7 +64,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/JSON/stringify

使用 JSON.stringify

-
JSON.stringify({});                        // '{}'
+
JSON.stringify({});                        // '{}'
 JSON.stringify(true);                      // 'true'
 JSON.stringify("foo");                     // '"foo"'
 JSON.stringify([1, "false", false]);       // '[1,"false",false]'
@@ -134,7 +134,7 @@ JSON.stringify(
 
 

例子(function)

-
function replacer(key, value) {
+
function replacer(key, value) {
   if (typeof value === "string") {
     return undefined;
   }
@@ -150,18 +150,18 @@ var jsonString = JSON.stringify(foo, replacer);

如果 replacer 是一个数组,数组的值代表将被序列化成 JSON 字符串的属性名。

-
JSON.stringify(foo, ['week', 'month']);
+
JSON.stringify(foo, ['week', 'month']);
 // '{"week":45,"month":7}', 只保留 “week” 和 “month” 属性值。

space 参数

space 参数用来控制结果字符串里面的间距。如果是一个数字, 则在字符串化时每一级别会比上一级别缩进多这个数字值的空格(最多10个空格);如果是一个字符串,则每一级别会比上一级别多缩进该字符串(或该字符串的前10个字符)。

-
JSON.stringify({ a: 2 }, null, " ");   // '{\n "a": 2\n}'
+
JSON.stringify({ a: 2 }, null, " ");   // '{\n "a": 2\n}'

使用制表符(\t)来缩进:

-
JSON.stringify({ uno: 1, dos : 2 }, null, '\t')
+
JSON.stringify({ uno: 1, dos : 2 }, null, '\t')
 // '{            \
 //     "uno": 1, \
 //     "dos": 2  \
@@ -172,7 +172,7 @@ var jsonString = JSON.stringify(foo, replacer);

如果一个被序列化的对象拥有 toJSON 方法,那么该 toJSON 方法就会覆盖该对象默认的序列化行为:不是该对象被序列化,而是调用 toJSON 方法后的返回值会被序列化,例如:

-
var obj = {
+
var obj = {
   foo: 'foo',
   toJSON: function () {
     return 'bar';
@@ -186,7 +186,7 @@ JSON.stringify({x: obj}); // '{"x":"bar"}'
 
 

注意 JSON 不是 JavaScript 严格意义上的子集,在 JSON 中不需要省略两条终线(Line separator 和 Paragraph separator),但在 JavaScript 中需要被省略。因此,如果 JSON 被用作 JSONP 时,下面方法可以使用:

-
function jsFriendlyJSONStringify (s) {
+
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"}

一些时候,你想存储用户创建的一个对象,并且,即使在浏览器被关闭后仍能恢复该对象。下面的例子是 JSON.stringify 适用于这种情形的一个样板:

-
// 创建一个示例数据
+
// 创建一个示例数据
 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
 
 

语法

-
myMap.forEach(callback([value][,key][,map])[, thisArg])
+
myMap.forEach(callback([value][,key][,map])[, thisArg])

参数

@@ -72,7 +72,7 @@ browser-compat: javascript.builtins.Map.forEach

以下的代码在每行中打印一个 Map 对象中的元素

-
function logMapElements(value, key, map) {
+
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
 
 

语法

-
myMap.keys()
+
myMap.keys()

返回值

@@ -32,7 +32,7 @@ browser-compat: javascript.builtins.Map.keys

使用 keys()

-
var myMap = new Map();
+
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
 
 

语法

-
Math.floor(x) 
+
Math.floor(x) 

参数

@@ -39,7 +39,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/floor

例子:使用 Math.floor

-
Math.floor( 45.95);
+
Math.floor( 45.95);
 // 45
 Math.floor( 45.05);
 // 45
@@ -54,7 +54,7 @@ Math.floor(-45.95);
 
 

例子:十进制调整

-
// Closure
+
// 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
 
 

语法

-
Math.random()
+
Math.random()

返回值

@@ -33,7 +33,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random

得到一个大于等于0,小于1之间的随机数

-
function getRandom() {
+
function getRandom() {
   return Math.random();
 }
@@ -41,7 +41,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random

这个例子返回了一个在指定值之间的随机数。这个值不小于 min(有可能等于),并且小于(不等于)max

-
function getRandomArbitrary(min, max) {
+
function getRandomArbitrary(min, max) {
   return Math.random() * (max - min) + min;
 }
 
@@ -50,7 +50,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random

这个例子返回了一个在指定值之间的随机整数。这个值不小于 min (如果 min 不是整数,则不小于 min 的向上取整数),且小于(不等于)max

-
function getRandomInt(min, max) {
+
function getRandomInt(min, max) {
   min = Math.ceil(min);
   max = Math.floor(max);
   return Math.floor(Math.random() * (max - min)) + min; //不含最大值,含最小值
@@ -64,7 +64,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/random
 
 

上一个例子提到的函数 getRandomInt() 结果范围包含了最小值,但不含最大值。如果你的随机结果需要同时包含最小值和最大值,怎么办呢?  getRandomIntInclusive() 函数可以实现。

-
function getRandomIntInclusive(min, max) {
+
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
 
 

语法

-
Math.sin(x)
+
Math.sin(x)

参数

@@ -30,7 +30,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/sin

例子:使用 Math.sin

-
Math.sin(0);           // 0
+
Math.sin(0);           // 0
 Math.sin(1);           // 0.8414709848078965
 
 Math.sin(Math.PI / 2); // 1
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

语法

-
Math.sinh(x)
+
Math.sinh(x)

参数

@@ -28,7 +28,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Math/sinh

示例

-
Math.sinh(0)      // 0
+
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
 
 

该函数可以使用 {{jsxref("Math.exp()")}} 函数来实现:

-
function sinh(x){
+
function sinh(x){
     return  (Math.exp(x) - Math.exp(-x)) / 2;
 }
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

语法

-
Number.isFinite(value)
+
Number.isFinite(value)

参数

@@ -36,13 +36,13 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Number/isFinite

Polyfill

-
if (Number.isFinite === undefined) Number.isFinite = function(value) {
+
if (Number.isFinite === undefined) Number.isFinite = function(value) {
     return typeof value === 'number' && isFinite(value);
 }

示例

-
Number.isFinite(Infinity);  // false
+
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
 
 

语法

-
new Number(value)
+
new Number(value)
 

参数

@@ -23,7 +23,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Number/Number

创建 Number 对象

-
const a = new Number('123'); // a === 123 is false
+
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
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

语法

-
Object.assign(target, ...sources)
+
Object.assign(target, ...sources)

参数

@@ -53,7 +53,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/assign

这个 polyfill 不支持 symbol 属性, 由于 ES5 中本来就不存在 symbols :

-
if (typeof Object.assign !== 'function') {
+
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
 
 

复制一个对象

-
const obj = { a: 1 };
+
const obj = { a: 1 };
 const copy = Object.assign({}, obj);
 console.log(copy); // { a: 1 }
 
@@ -98,7 +98,7 @@ console.log(copy); // { a: 1 }

假如源值是一个对象的引用,它仅仅会复制其引用值。

-
const log = console.log;
+
const log = console.log;
 
 function test() {
   'use strict';
@@ -139,7 +139,7 @@ test();
 
 

合并对象

-
const o1 = { a: 1 };
+
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 }, 注意目标对象自身也会改变
 
 

合并具有相同属性的对象

-
const o1 = { a: 1, b: 1, c: 1 };
+
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 }

拷贝 symbol 类型的属性

-
const o1 = { a: 1 };
+
const o1 = { a: 1 };
 const o2 = { [Symbol('foo')]: 2 };
 
 const obj = Object.assign({}, o1, o2);
@@ -170,7 +170,7 @@ Object.getOwnPropertySymbols(obj); // [Symbol(foo)]

继承属性和不可枚举属性是不能拷贝的

-
const obj = Object.create({foo: 1}, { // foo 是个继承属性。
+
const obj = Object.create({foo: 1}, { // foo 是个继承属性。
     bar: {
         value: 2  // bar 是个不可枚举属性。
     },
@@ -186,7 +186,7 @@ console.log(copy); // { baz: 3 }
 
 

原始类型会被包装为对象

-
const v1 = "abc";
+
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" }

异常会打断后续拷贝任务

-
const target = Object.defineProperty({}, "foo", {
+
const target = Object.defineProperty({}, "foo", {
     value: 1,
     writable: false
 }); // target 的 foo 属性是个只读属性。
@@ -216,7 +216,7 @@ console.log(target.baz);  // undefined,第三个源对象更是不会被拷贝
 
 

拷贝访问器

-
const obj = {
+
const obj = {
   foo: 1,
   get bar() {
     return 2;
@@ -255,7 +255,7 @@ console.log(copy);
 
 

此{{Glossary("Polyfill","polyfill")}}不支持 symbol 属性,因为ES5 中根本没有 symbol :

-
if (typeof Object.assign != 'function') {
+
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
 
 

语法

-
Object.create(proto,[propertiesObject])
+
Object.create(proto,[propertiesObject])

参数

@@ -45,7 +45,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/create

下面的例子演示了如何使用Object.create()来实现类式继承。这是一个所有版本JavaScript都支持的单继承。

-
// Shape - 父类(superclass)
+
// Shape - 父类(superclass)
 function Shape() {
   this.x = 0;
   this.y = 0;
@@ -77,7 +77,7 @@ rect.move(1, 1); // Outputs, 'Shape moved.'

如果你希望能继承到多个对象,则可以使用混入的方式。

-
function MyClass() {
+
function MyClass() {
      SuperClass.call(this);
      OtherSuperClass.call(this);
 }
@@ -98,7 +98,7 @@ MyClass.prototype.myMethod = function() {
 
 

使用 Object.createpropertyObject参数

-
var o;
+
var o;
 
 // 创建一个原型为null的空对象
 o = Object.create(null);
@@ -167,7 +167,7 @@ o2 = Object.create({}, {
 
 

请注意,尽管在 ES5 中 Object.create支持设置为[[Prototype]]null,但因为那些ECMAScript5以前版本限制,此 polyfill 无法支持该特性。

-
if (typeof Object.create !== "function") {
+
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
 
 

语法

-
Object.defineProperties(objprops)
+
Object.defineProperties(objprops)

参数

@@ -63,7 +63,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperties

例子

-
var obj = {};
+
var obj = {};
 Object.defineProperties(obj, {
   'property1': {
     value: true,
@@ -80,7 +80,7 @@ Object.defineProperties(obj, {
 
 

假设一个原始的执行环境,所有的名称和属性都引用它们的初始值,Object.defineProperties几乎完全等同于(注意isCallable中的注释)以下JavaScript中的重新实现:

-
function defineProperties(obj, properties) {
+
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
 
 

语法

-
Object.defineProperty(obj, prop, descriptor)
+
Object.defineProperty(obj, prop, descriptor)

参数

@@ -135,7 +135,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/defineProperty

记住,这些选项不一定是自身属性,也要考虑继承来的属性。为了确认保留这些默认值,在设置之前,可能要冻结 {{jsxref("Object.prototype")}},明确指定所有的选项,或者通过 {{jsxref("Object.create", "Object.create(null)")}} 将 {{jsxref("Object.prototype.__proto__", "__proto__")}} 属性指向 {{jsxref("null")}}。

-
// 使用 __proto__
+
// 使用 __proto__
 var obj = {};
 var descriptor = Object.create(null); // 没有继承的属性
 // 默认没有 enumerable,没有 configurable,没有 writable
@@ -178,7 +178,7 @@ Object.defineProperty(obj, "key", withValue("static"));
 
 

如果对象中不存在指定的属性,Object.defineProperty() 会创建这个属性。当描述符中省略某些字段时,这些字段将使用它们的默认值。

-
var o = {}; // 创建一个新对象
+
var o = {}; // 创建一个新对象
 
 // 在对象中添加一个属性与数据描述符的示例
 Object.defineProperty(o, "a", {
@@ -225,7 +225,7 @@ Object.defineProperty(o, "conflict", {
 
 

writable 属性设置为 false 时,该属性被称为“不可写的”。它不能被重新赋值。

-
var o = {}; // 创建一个新对象
+
var o = {}; // 创建一个新对象
 
 Object.defineProperty(o, 'a', {
   value: 37,
@@ -256,7 +256,7 @@ console.log(o.a); // logs 37. The assignment didn't work.
 
 

enumerable 定义了对象的属性是否可以在 {{jsxref("Statements/for...in", "for...in")}} 循环和 {{jsxref("Object.keys()")}} 中被枚举。

-
var o = {};
+
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

configurable 特性表示对象的属性是否可以被删除,以及除 valuewritable 特性外的其他特性是否可以被修改。

-
var o = {};
+
var o = {};
 Object.defineProperty(o, 'a', {
   get() { return 1; },
   configurable: false
@@ -329,7 +329,7 @@ console.log(o.a); // logs 1

考虑特性被赋予的默认特性值非常重要,通常,使用点运算符和 Object.defineProperty() 为对象的属性赋值时,数据描述符中的属性默认值是不同的,如下例所示。

-
var o = {};
+
var o = {};
 
 o.a = 1;
 // 等同于:
@@ -356,7 +356,7 @@ Object.defineProperty(o, "a", {
 
 

下面的例子展示了如何实现一个自存档对象。当设置temperature 属性时,archive 数组会收到日志条目。

-
function Archiver() {
+
function Archiver() {
   var temperature = null;
   var archive = [];
 
@@ -382,7 +382,7 @@ arc.getArchive(); // [{ val: 11 }, { val: 13 }]

下面这个例子中,getter 总是会返回一个相同的值。

-
var pattern = {
+
var pattern = {
     get: function () {
         return 'I alway return this string,whatever you have assigned';
     },
@@ -409,7 +409,7 @@ console.log(instance.myname);

如果访问者的属性是被继承的,它的 getset 方法会在子对象的属性被访问或者修改时被调用。如果这些方法用一个变量存值,该值会被所有对象共享。

-
function myclass() {
+
function myclass() {
 }
 
 var value;
@@ -430,7 +430,7 @@ console.log(b.x); // 1
 
 

这可以通过将值存储在另一个属性中解决。在 getset 方法中,this 指向某个被访问和修改属性的对象。

-
function myclass() {
+
function myclass() {
 }
 
 Object.defineProperty(myclass.prototype, "x", {
@@ -449,7 +449,7 @@ console.log(b.x); // undefined

不像访问者属性,值属性始终在对象自身上设置,而不是一个原型。然而,如果一个不可写的属性被继承,它仍然可以防止修改对象的属性。

-
function myclass() {
+
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
 
 

语法

-
Object.fromEntries(iterable);
+
Object.fromEntries(iterable);

参数

@@ -38,7 +38,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/fromEntries

通过 Object.fromEntries, 可以将 {{jsxref("Map")}} 转换为 {{jsxref("Object")}}:

-
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
+
const map = new Map([ ['foo', 'bar'], ['baz', 42] ]);
 const obj = Object.fromEntries(map);
 console.log(obj); // { foo: "bar", baz: 42 }
 
@@ -47,7 +47,7 @@ console.log(obj); // { foo: "bar", baz: 42 }

通过 Object.fromEntries, 可以将 {{jsxref("Array")}} 转换为 {{jsxref("Object")}}:

-
const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
+
const arr = [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ];
 const obj = Object.fromEntries(arr);
 console.log(obj); // { 0: "a", 1: "b", 2: "c" }
 
@@ -56,7 +56,7 @@ console.log(obj); // { 0: "a", 1: "b", 2: "c" }

Object.fromEntries 是与 {{jsxref("Object.entries()")}} 相反的方法,用 数组处理函数 可以像下面这样转换对象:

-
const object1 = { a: 1, b: 2, c: 3 };
+
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
 
 

语法

-
Object.getOwnPropertyDescriptor(obj, prop)
+
Object.getOwnPropertyDescriptor(obj, prop)

参数

@@ -54,7 +54,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/getOwnPropertyDes

示例

-
var o, d;
+
var o, d;
 
 o = { get foo() { return 17; } };
 d = Object.getOwnPropertyDescriptor(o, "foo");
@@ -92,7 +92,7 @@ d = Object.getOwnPropertyDescriptor(o, "baz");
 
 

在 ES5 中,如果该方法的第一个参数不是对象(而是原始类型),那么就会产生出现 {{jsxref("TypeError")}}。而在 ES2015,第一个的参数不是对象的话就会被强制转换为对象。

-
Object.getOwnPropertyDescriptor('foo', 0);
+
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
 
 

语法

-
obj.hasOwnProperty(prop)
+
obj.hasOwnProperty(prop)

参数

@@ -43,7 +43,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

即使属性的值是 nullundefined,只要属性存在,hasOwnProperty 依旧会返回 true

-
o = new Object();
+
o = new Object();
 o.propOne = null;
 o.hasOwnProperty('propOne'); // 返回 true
 o.propTwo = undefined;
@@ -56,7 +56,7 @@ o.hasOwnProperty('propTwo'); // 返回 true
 
 

下面的例子检测了对象 o 是否含有自身属性 prop

-
o = new Object();
+
o = new Object();
 o.hasOwnProperty('prop'); // 返回 false
 o.prop = 'exists';
 o.hasOwnProperty('prop'); // 返回 true
@@ -68,7 +68,7 @@ o.hasOwnProperty('prop'); // 返回 false
 
 

下面的例子演示了 hasOwnProperty 方法对待自身属性和继承属性的区别:

-
o = new Object();
+
o = new Object();
 o.prop = 'exists';
 o.hasOwnProperty('prop');             // 返回 true
 o.hasOwnProperty('toString');         // 返回 false
@@ -79,7 +79,7 @@ o.hasOwnProperty('hasOwnProperty');   // 返回 false
 
 

下面的例子演示了如何在遍历一个对象的所有属性时忽略掉继承属性,注意这里 {{jsxref("Statements/for...in", "for...in")}}  循环只会遍历可枚举属性,所以不应该基于这个循环中没有不可枚举的属性而得出 hasOwnProperty 是严格限制于可枚举项目的(如同 {{jsxref("Object.getOwnPropertyNames()")}})。

-
var buz = {
+
var buz = {
   fog: 'stack'
 };
 
@@ -98,7 +98,7 @@ for (var name in buz) {
 
 

JavaScript 并没有保护 hasOwnProperty 这个属性名,因此,当某个对象可能自有一个占用该属性名的属性时,就需要使用外部的 hasOwnProperty 获得正确的结果:

-
var foo = {
+
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
 
 

下面的例子将一个空的 Object 对象存到 o 中:

-
var o = new Object();
+
var o = new Object();
 
-
var o = new Object(undefined);
+
var o = new Object(undefined);
 
-
var o = new Object(null);
+
var o = new Object(null);
 

使用 Object 生成布尔对象

下面的例子将{{jsxref("Boolean")}} 对象存到 o 中:

-
// 等价于 o = new Boolean(true);
+
// 等价于 o = new Boolean(true);
 var o = new Object(true);
 
-
// 等价于 o = new Boolean(false);
+
// 等价于 o = new Boolean(false);
 var o = new Object(Boolean());
 
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

语法

-

Object.is(value1, value2);
+

Object.is(value1, value2);

参数

@@ -59,7 +59,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/is

Polyfill

-
if (!Object.is) {
+
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
 
 

使用 Object.is

-
Object.is('foo', 'foo');     // true
+
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
 
 

语法

-
Object.isSealed(obj)
+
Object.isSealed(obj)

参数

@@ -33,7 +33,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Object/isSealed

例子

-
// 新建的对象默认不是密封的.
+
// 新建的对象默认不是密封的.
 var empty = {};
 Object.isSealed(empty); // === false
 
@@ -72,7 +72,7 @@ Object.isFrozen(s3); // === true ,访问器属性不考虑可写不可写,只
 
 

在ES5中,如果这个方法的参数不是一个对象(一个原始类型),那么它会导致{{jsxref("TypeError")}}。在ES2015中,非对象参数将被视为是一个密封的普通对象,只返回true

-
Object.isSealed(1);
+
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
 
 

语法

-
parseInt(string, radix);
+
parseInt(string, radix);

参数

@@ -48,7 +48,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/parseInt
  • 第一个非空格字符不能转换为数字。
  • -
    parseInt('123', 5) // 将'123'看作5进制数,返回十进制数38 => 1*5^2 + 2*5^1 + 3*5^0 = 38
    +
    parseInt('123', 5) // 将'123'看作5进制数,返回十进制数38 => 1*5^2 + 2*5^1 + 3*5^0 = 38

    描述

    @@ -89,7 +89,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/parseInt

    以下例子均返回15:

    -
    parseInt("0xF", 16);
    +
    parseInt("0xF", 16);
     parseInt("F", 16);
     parseInt("17", 8);
     parseInt(021, 8);
    @@ -105,13 +105,13 @@ parseInt("12", 13);

    以下例子均返回 NaN:

    -
    parseInt("Hello", 8); // 根本就不是数值
    +
    parseInt("Hello", 8); // 根本就不是数值
     parseInt("546", 2);   // 除了“0、1”外,其它数字都不是有效二进制数字
     

    以下例子均返回 -15

    -
    parseInt("-F", 16);
    +
    parseInt("-F", 16);
     parseInt("-0F", 16);
     parseInt("-0XF", 16);
     parseInt(-15.1, 10);
    @@ -124,19 +124,19 @@ parseInt("-12", 13);
     
     

    下例中全部返回 4:

    -
    parseInt(4.7, 10);
    +
    parseInt(4.7, 10);
     parseInt(4.7 * 1e22, 10); // 非常大的数值变成 4
     parseInt(0.00000000000434, 10); // 非常小的数值变成 4

    下面的例子返回 224

    -
    parseInt("0e0",16);
    +
    parseInt("0e0",16);

    没有指定 radix 参数时的八进制解析

    尽管 ECMAScript 3 已经不赞成这种做法,且 ECMAScript 5 已经禁止了这种做法,但是仍然有很多实现环境仍然把以 0 开头的数值字符串(numeric string)解释为一个八进制数。下面的例子可能返回八进制的结果,也可能返回十进制的结果。总是指定一个基数(radix)可以避免这种不可靠的行为。

    -
    parseInt("0e0");
    +
    parseInt("0e0");
     // 0
     
     parseInt("08");
    @@ -157,7 +157,7 @@ parseInt("08");
     
     

    有时采用一个更严格的方法来解析整型值很有用。此时可以使用正则表达式:

    -
    filterInt = function (value) {
    +
    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
     
     

    语法

    -
    Promise.all(iterable);
    +
    Promise.all(iterable);

    参数

    @@ -56,7 +56,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise/all

    Promise.all 等待所有都完成(或第一个失败)。

    -
    var p1 = Promise.resolve(3);
    +
    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 => {
     
     

    如果参数中包含非 promise 值,这些值将被忽略,但仍然会被放在返回数组中(如果 promise 完成的话):

    -
    // this will be counted as if the iterable passed is empty, so it gets fulfilled
    +
    // 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(){
     
     

    下面的例子中演示了 Promise.all 的异步性(如果传入的可迭代对象是空的,就是同步):

    -
    // we are passing as argument an array of promises that are already resolved,
    +
    // 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(){
     
     

    如果 Promise.all 失败,也是一样的:

    -
    var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)];
    +
    var mixedPromisesArray = [Promise.resolve(33), Promise.reject(44)];
     var p = Promise.all(mixedPromisesArray);
     console.log(p);
     setTimeout(function(){
    @@ -129,7 +129,7 @@ setTimeout(function(){
     
     

    但是,Promise.all 当且仅当传入的可迭代对象为空时为同步:

    -
    var p = Promise.all([]); // will be immediately resolved
    +
    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(){
     
     

    Promise.all 在任意一个传入的 promise 失败时返回失败。例如,如果你传入的 promise中,有四个 promise 在一定的时间之后调用成功函数,有一个立即调用失败函数,那么 Promise.all 将立即变为失败。

    -
    var p1 = new Promise((resolve, reject) => {
    +
    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
     
     

    句法

    -
    Promise.allSettled(iterable);
    +
    Promise.allSettled(iterable);

    参数

    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

    语法

    -
    Promise.any(iterable);
    +
    Promise.any(iterable);

    参数

    @@ -63,7 +63,7 @@ translation_of: Web/JavaScript/Reference/Global_Objects/Promise/any

    即使第一个返回的 promise 是失败的,Promise.any() 依然使用第一个成功状态的 promise 来返回。这与使用首个(无论 rejected 还是 fullfiled)promise 来返回的 {{jsxref("Promise.race()")}} 相反。

    -
    const pErr = new Promise((resolve, reject) => {
    +
    const pErr = new Promise((resolve, reject) => {
       reject("总是失败");
     });
     
    @@ -86,7 +86,7 @@ Promise.any([pErr, pSlow, pFast]).then((value) => {
     
     

    如果没有 fulfilled (成功的) promise,Promise.any() 返回 {{jsxref("AggregateError")}} 错误。

    -
    const pErr = new Promise((resolve, reject) => {
    +
    const pErr = new Promise((resolve, reject) => {
       reject('总是失败');
     });
     
    @@ -100,7 +100,7 @@ Promise.any([pErr]).catch((err) => {
     
     

    在这个例子,我们有一个获取图片并返回 blob 的函数,我们使用 Promise.any() 来获取一些图片并显示第一张有效的图片(即最先 resolved 的那个 promise)。

    -
    function fetchAndDecode(url) {
    +
    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
     
     

    我们可以用 promise.then()promise.catch()promise.finally() 这些方法将进一步的操作与一个变为已敲定状态的 promise 关联起来。这些方法还会返回一个新生成的 promise 对象,这个对象可以被非强制性的用来做链式调用,就像这样:

    -
    const myPromise =
    +
    const myPromise =
       (new Promise(myExecutorFunc))
       .then(handleFulfilledA,handleRejectedA)
       .then(handleFulfilledB,handleRejectedB)
    @@ -65,7 +65,7 @@ const myPromise =
     
     

    这两个函数的签名很简单,它们只接受一个任意类型的参数。这些函数由您(编程者)编写。这些函数的终止状态决定着链式调用中下一个promise的"已敲定 (settled)"状态是什么。任何不是 throw 的终止都会创建一个"已决议(resolved)"状态,而以 throw 终止则会创建一个"已拒绝"状态。

    -
    handleFulfilled(value)       { /*...*/; return nextValue;  }
    +
    handleFulfilled(value)       { /*...*/; return nextValue;  }
     handleRejection(reason)  { /*...*/; throw  nextReason; }
     handleRejection(reason)  { /*...*/; return nextValue;  }
    @@ -75,21 +75,21 @@ handleRejection(reason) { /*...*/; return nextValue; }

    链式调用中的 promise 们就像俄罗斯套娃一样,是嵌套起来的,但又像是一个栈,每个都必须从顶端被弹出。链式调用中的第一个 promise 是嵌套最深的一个,也将是第一个被弹出的。

    -
    (promise D, (promise C, (promise B, (promise A) ) ) )
    +
    (promise D, (promise C, (promise B, (promise A) ) ) )

    当存在一个 nextValue 是 promise 时,就会出现一种动态的替换效果。return 会导致一个 promise 被弹出,但这个 nextValue promise 则会被推入被弹出 promise 原来的位置。对于上面所示的嵌套场景,假设与 "promise B" 相关的 .then() 返回了一个值为 "promise X" 的 nextValue 。那么嵌套的结果看起来就会是这样:

    -
    (promise D, (promise C, (promise X) ) )
    +
    (promise D, (promise C, (promise X) ) )

    一个 promise 可能会参与不止一次的嵌套。对于下面的代码,promiseA 向"已敲定"("settled")状态的过渡会导致两个实例的 .then 都被调用。

    -
    const promiseA = new Promise(myExecutorFunc);
    +
    const promiseA = new Promise(myExecutorFunc);
     const promiseB = promiseA.then(handleFulfilled1, handleRejected1);
     const promiseC = promiseA.then(handleFulfilled2, handleRejected2); 

    一个已经处于"已敲定"("settled")状态的 promise 也可以接收操作。在那种情况下,(如果没有问题的话,)这个操作会被作为第一个异步操作被执行。注意,所有的 promise 都一定是异步的。因此,一个已经处于"已敲定"("settled")状态的 promise 中的操作只有 promise 链式调用的栈被清空了和一个事件循环过去了之后才会被执行。这种效果跟 setTimeout(action, 10) 特别相似。

    -
    const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
    +
    const promiseA = new Promise( (resolutionFunc,rejectionFunc) => {
         resolutionFunc(777);
     });
     // 这时,"promiseA" 已经被敲定了。
    @@ -155,7 +155,7 @@ console.log("immediate logging");
     
     

    Promise 对象是由关键字 new 及其构造函数来创建的。该构造函数会把一个叫做“处理器函数”(executor function)的函数作为它的参数。这个“处理器函数”接受两个函数——resolve 和 reject ——作为其参数。当异步任务顺利完成且返回结果值时,会调用 resolve 函数;而当异步任务失败且返回失败原因(通常是一个错误对象)时,会调用reject 函数。

    -
    const myFirstPromise = new Promise((resolve, reject) => {
    +
    const myFirstPromise = new Promise((resolve, reject) => {
       // ?做一些异步操作,最终会调用下面两者之一:
       //
       //   resolve(someValue); // fulfilled
    @@ -165,7 +165,7 @@ console.log("immediate logging");
     
     

    想要某个函数拥有promise功能,只需让其返回一个promise即可。

    -
    function myAsyncFunction(url) {
    +
    function myAsyncFunction(url) {
       return new Promise((resolve, reject) => {
         const xhr = new XMLHttpRequest();
         xhr.open("GET", url);
    @@ -179,7 +179,7 @@ console.log("immediate logging");
     
     

    基础示例

    -
    let myFirstPromise = new Promise(function(resolve, reject){
    +
    let myFirstPromise = new Promise(function(resolve, reject){
         //当异步代码执行成功时,我们才会调用resolve(...), 当异步代码失败时就会调用reject(...)
         //在本例中,我们使用setTimeout(...)来模拟异步代码,实际编码时可能是XHR请求或是HTML5的一些API方法.
         setTimeout(function(){
    @@ -196,7 +196,7 @@ myFirstPromise.then(function(successMessage){
     
     

    高级示例

    -