diff --git a/.github/workflows/reviewdog.yml b/.github/workflows/reviewdog.yml new file mode 100644 index 00000000000000..3b5094e9fecf63 --- /dev/null +++ b/.github/workflows/reviewdog.yml @@ -0,0 +1,45 @@ +name: reviewdog + +on: + - pull_request + +jobs: + prettier: + # do not run on forks + if: github.repository == 'mdn/translated-content' + name: prettier + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Get changed files + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + HEAD_SHA: ${{ github.event.pull_request.head.sha }} + run: | + # Use the GitHub API to get the list of changed files + # documenation: https://docs.github.com/rest/commits/commits#compare-two-commits + DIFF_DOCUMENTS=$(gh api repos/{owner}/{repo}/compare/${{ env.BASE_SHA }}...${{ env.HEAD_SHA }} --jq '.files | .[] | select(.status|IN("added", "modified", "renamed", "copied", "changed")) | .filename' | xargs) + echo "DIFF_DOCUMENTS=${DIFF_DOCUMENTS}" >> $GITHUB_ENV + + - name: Setup Node.js environment + uses: actions/setup-node@v3 + with: + node-version-file: ".nvmrc" + cache: yarn + + - name: Install all yarn packages + run: yarn --frozen-lockfile + env: + # https://github.com/microsoft/vscode-ripgrep#github-api-limit-note + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + + - name: Perform linting + run: yarn prettier --ignore-unknown --write ${{ env.DIFF_DOCUMENTS }} + + - name: Submit suggestion + uses: reviewdog/action-suggester@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + tool_name: prettier diff --git a/files/zh-cn/web/api/htmlformelement/formdata_event/index.md b/files/zh-cn/web/api/htmlformelement/formdata_event/index.md index 1c8423519e6536..90f227967950db 100644 --- a/files/zh-cn/web/api/htmlformelement/formdata_event/index.md +++ b/files/zh-cn/web/api/htmlformelement/formdata_event/index.md @@ -22,11 +22,11 @@ target.onformdata = functionRef; ```js // grab reference to form -const formElem = document.querySelector('form'); +const formElem = document.querySelector("form"); // submit handler -formElem.addEventListener('submit', (e) => { +formElem.addEventListener("submit", (e) => { // on form submission, prevent default e.preventDefault(); @@ -37,7 +37,7 @@ formElem.addEventListener('submit', (e) => { // formdata handler to retrieve data formElem.onformdata = (e) => { - console.log('formdata fired'); + console.log("formdata fired"); // Get the form data from the event object let data = e.formData; diff --git a/files/zh-cn/web/api/htmlformelement/index.md b/files/zh-cn/web/api/htmlformelement/index.md index 614bad4dbd8185..514edf5d3e6250 100644 --- a/files/zh-cn/web/api/htmlformelement/index.md +++ b/files/zh-cn/web/api/htmlformelement/index.md @@ -64,7 +64,7 @@ document.body.appendChild(f); // Add action and method attributes f.action = "/cgi-bin/some.cgi"; -f.method = "POST" +f.method = "POST"; // Call the form's submit method f.submit(); @@ -80,16 +80,34 @@ In addition, the following complete HTML document shows how to extract informati // Get a reference using the forms collection var f = document.forms["formA"]; - info = "f.elements: " + f.elements + "\n" - + "f.length: " + f.length + "\n" - + "f.name: " + f.name + "\n" - + "f.acceptCharset: " + f.acceptCharset + "\n" - + "f.action: " + f.action + "\n" - + "f.enctype: " + f.enctype + "\n" - + "f.encoding: " + f.encoding + "\n" - + "f.method: " + f.method + "\n" - + "f.target: " + f.target; - document.forms["formA"].elements['tex'].value = info; + info = + "f.elements: " + + f.elements + + "\n" + + "f.length: " + + f.length + + "\n" + + "f.name: " + + f.name + + "\n" + + "f.acceptCharset: " + + f.acceptCharset + + "\n" + + "f.action: " + + f.action + + "\n" + + "f.enctype: " + + f.enctype + + "\n" + + "f.encoding: " + + f.encoding + + "\n" + + "f.method: " + + f.method + + "\n" + + "f.target: " + + f.target; + document.forms["formA"].elements["tex"].value = info; } // A reference to the form is passed from the @@ -97,27 +115,24 @@ In addition, the following complete HTML document shows how to extract informati function setFormInfo(f) { f.method = "GET"; f.action = "/cgi-bin/evil_executable.cgi"; - f.name = "totally_new"; + f.name = "totally_new"; } -

Form example

- -
-

Click "Info" to see information about the form. - Click set to change settings, then info again - to see their effect

-

- - - -
- -

+

Form example

+ + +

+ Click "Info" to see information about the form. Click set to change + settings, then info again to see their effect +

+

+ + + +
+ +

``` @@ -126,45 +141,77 @@ The following example shows how to submit a form in a [popup window](/zh-CN/docs ```html - - -MDN Example - - - - - - -
-

First name:
- Last name:
- Password:
- Male Female

-

I have a bike
- I have a car

-

-
- - + + + MDN Example + + + + +
+

+ First name:
+ Last name:
+ Password:
+ Male + Female +

+

+ I have a bike
+ I have a car +

+

+
+ ``` diff --git a/files/zh-cn/web/api/htmlformelement/reportvalidity/index.md b/files/zh-cn/web/api/htmlformelement/reportvalidity/index.md index 313db0bd1dc33b..3761a89a5ca465 100644 --- a/files/zh-cn/web/api/htmlformelement/reportvalidity/index.md +++ b/files/zh-cn/web/api/htmlformelement/reportvalidity/index.md @@ -20,13 +20,21 @@ HTMLFormElement.reportValidity() ## Example ```js -document.forms['myform'].addEventListener('invalid', function() { - // Optional response here -}, false); - -document.forms['myform'].addEventListener('submit', function() { - document.forms['myform'].reportValidity(); -}, false); +document.forms["myform"].addEventListener( + "invalid", + function () { + // Optional response here + }, + false, +); + +document.forms["myform"].addEventListener( + "submit", + function () { + document.forms["myform"].reportValidity(); + }, + false, +); ``` ## Specifications diff --git a/files/zh-cn/web/api/htmlformelement/requestsubmit/index.md b/files/zh-cn/web/api/htmlformelement/requestsubmit/index.md index 3efffcdb7f7094..63f18200bba607 100644 --- a/files/zh-cn/web/api/htmlformelement/requestsubmit/index.md +++ b/files/zh-cn/web/api/htmlformelement/requestsubmit/index.md @@ -9,7 +9,7 @@ slug: Web/API/HTMLFormElement/requestSubmit ## 语法 -```js +```js-nolint requestSubmit() requestSubmit(submitter) ``` diff --git a/files/zh-cn/web/api/htmlformelement/reset_event/index.md b/files/zh-cn/web/api/htmlformelement/reset_event/index.md index 6be4b65da39e97..991d1c9e27beb1 100644 --- a/files/zh-cn/web/api/htmlformelement/reset_event/index.md +++ b/files/zh-cn/web/api/htmlformelement/reset_event/index.md @@ -22,12 +22,12 @@ slug: Web/API/HTMLFormElement/reset_event ## 属性 -| Property | Type | Description | -| ------------------------------------- | ------------------------------------ | ---------------------------------- | +| Property | Type | Description | +| ------------------------------- | -------------------------- | ---------------------------------- | | `target` {{readonlyInline}} | {{domxref("EventTarget")}} | 事件的目标(DOM 树最顶端的元素)。 | -| `type` {{readonlyInline}} | {{domxref("DOMString")}} | 事件的类型。 | -| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | 是否指定事件冒泡。 | -| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | 事件是否可以被取消。 | +| `type` {{readonlyInline}} | {{domxref("DOMString")}} | 事件的类型。 | +| `bubbles` {{readonlyInline}} | {{jsxref("Boolean")}} | 是否指定事件冒泡。 | +| `cancelable` {{readonlyInline}} | {{jsxref("Boolean")}} | 事件是否可以被取消。 | ## 规范 diff --git a/files/zh-cn/web/api/htmlformelement/submit/index.md b/files/zh-cn/web/api/htmlformelement/submit/index.md index a6cba238d2868b..1457199a251e02 100644 --- a/files/zh-cn/web/api/htmlformelement/submit/index.md +++ b/files/zh-cn/web/api/htmlformelement/submit/index.md @@ -20,7 +20,7 @@ slug: Web/API/HTMLFormElement/submit ## 语法 - ```js +```js-nolint submit() ``` diff --git a/files/zh-cn/web/api/htmlformelement/submit_event/index.md b/files/zh-cn/web/api/htmlformelement/submit_event/index.md index e0e6d718d457c9..817628700a84c6 100644 --- a/files/zh-cn/web/api/htmlformelement/submit_event/index.md +++ b/files/zh-cn/web/api/htmlformelement/submit_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLFormElement: submit event' +title: "HTMLFormElement: submit event" slug: Web/API/HTMLFormElement/submit_event --- @@ -42,8 +42,8 @@ slug: Web/API/HTMLFormElement/submit_event ```html
- -

+ +

@@ -57,9 +57,9 @@ function logSubmit(event) { event.preventDefault(); } -const form = document.getElementById('form'); -const log = document.getElementById('log'); -form.addEventListener('submit', logSubmit); +const form = document.getElementById("form"); +const log = document.getElementById("log"); +form.addEventListener("submit", logSubmit); ``` ### 结果 diff --git a/files/zh-cn/web/api/htmlimageelement/decode/index.md b/files/zh-cn/web/api/htmlimageelement/decode/index.md index d02ac8790ea735..11a3bd70013bc3 100644 --- a/files/zh-cn/web/api/htmlimageelement/decode/index.md +++ b/files/zh-cn/web/api/htmlimageelement/decode/index.md @@ -35,14 +35,15 @@ var promise = HTMLImageElement.decode(); ```js const img = new Image(); -img.src = 'nebula.jpg'; -img.decode() -.then(() => { - document.body.appendChild(img); -}) -.catch((encodingError) => { - // Do something with the error. -}) +img.src = "nebula.jpg"; +img + .decode() + .then(() => { + document.body.appendChild(img); + }) + .catch((encodingError) => { + // Do something with the error. + }); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlimageelement/decoding/index.md b/files/zh-cn/web/api/htmlimageelement/decoding/index.md index 17566534e97ef1..05a917b593f09b 100644 --- a/files/zh-cn/web/api/htmlimageelement/decoding/index.md +++ b/files/zh-cn/web/api/htmlimageelement/decoding/index.md @@ -28,8 +28,8 @@ imgElem.decoding = refStr; ```js var img = new Image(); -img.decoding = 'sync'; -img.src = 'img/logo.png'; +img.decoding = "sync"; +img.src = "img/logo.png"; ``` ## Specifications diff --git a/files/zh-cn/web/api/htmlimageelement/image/index.md b/files/zh-cn/web/api/htmlimageelement/image/index.md index 37abab4fb9deaa..146be0f41bd1d0 100644 --- a/files/zh-cn/web/api/htmlimageelement/image/index.md +++ b/files/zh-cn/web/api/htmlimageelement/image/index.md @@ -26,14 +26,14 @@ Image(width, height) ```js var myImage = new Image(100, 200); -myImage.src = 'picture.jpg'; +myImage.src = "picture.jpg"; document.body.appendChild(myImage); ``` 上面的代码相当于在 {{htmlelement("body")}}中定义了下面的 HTML: ```html - + ``` > **备注:** 无论构造函数中指定的大小是多少,都会加载整个位图。如果在构造时指定了尺寸信息,那么将会反应在实例的 {{domxref("HTMLImageElement.width")}} 和 {{domxref("HTMLImageElement.height")}} 属性上。图像自身的 CSS 像素值将会反应在{{domxref("HTMLImageElement.naturalWidth")}} 和 {{domxref("HTMLImageElement.naturalHeight")}}属性。如果没有指定值,那么两个属性的值相同 diff --git a/files/zh-cn/web/api/htmlimageelement/index.md b/files/zh-cn/web/api/htmlimageelement/index.md index 47ce75384ed482..c9b88276dd3339 100644 --- a/files/zh-cn/web/api/htmlimageelement/index.md +++ b/files/zh-cn/web/api/htmlimageelement/index.md @@ -92,13 +92,13 @@ If an error occurs while trying to load or render the image, and an [`onerror`]( ```js var img1 = new Image(); // Image 构造器 -img1.src = 'image1.png'; -img1.alt = 'alt'; +img1.src = "image1.png"; +img1.alt = "alt"; document.body.appendChild(img1); -var img2 = document.createElement('img'); // 使用 DOM HTMLImageElement -img2.src = 'image2.jpg'; -img2.alt = 'alt text'; +var img2 = document.createElement("img"); // 使用 DOM HTMLImageElement +img2.src = "image2.jpg"; +img2.alt = "alt text"; document.body.appendChild(img2); // 使用文档中的第一个 img diff --git a/files/zh-cn/web/api/htmlimageelement/naturalheight/index.md b/files/zh-cn/web/api/htmlimageelement/naturalheight/index.md index 6a766dfd522d46..0342d4f03f4691 100644 --- a/files/zh-cn/web/api/htmlimageelement/naturalheight/index.md +++ b/files/zh-cn/web/api/htmlimageelement/naturalheight/index.md @@ -25,10 +25,11 @@ slug: Web/API/HTMLImageElement/naturalHeight ```html
- -
-
+
+
``` HTML 具有一个 400x398 像素的图像,该图像放置在一个 {{HTMLElement("div")}} 元素中。 @@ -58,11 +59,12 @@ HTML 具有一个 400x398 像素的图像,该图像放置在一个 {{HTMLEleme let output = document.querySelector(".output"); let image = document.querySelector("img"); -window.addEventListener("load", event => { - output.innerHTML += `Natural size: ${image.naturalWidth} x ` + - `${image.naturalHeight} pixels
`; - output.innerHTML += `Displayed size: ${image.width} x ` + - `${image.height} pixels`; +window.addEventListener("load", (event) => { + output.innerHTML += + `Natural size: ${image.naturalWidth} x ` + + `${image.naturalHeight} pixels
`; + output.innerHTML += + `Displayed size: ${image.width} x ` + `${image.height} pixels`; }); ``` diff --git a/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.md b/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.md index beda5b84318fd7..8140876b209843 100644 --- a/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.md +++ b/files/zh-cn/web/api/htmlimageelement/referrerpolicy/index.md @@ -24,10 +24,10 @@ imgElt.referrerPolicy = refStr; ```js var img = new Image(); -img.src = 'img/logo.png'; -img.referrerPolicy = 'origin'; +img.src = "img/logo.png"; +img.referrerPolicy = "origin"; -var div = document.getElementById('divAround'); +var div = document.getElementById("divAround"); div.appendChild(img); // Fetch the image using the origin as the referrer ``` diff --git a/files/zh-cn/web/api/htmlimageelement/srcset/index.md b/files/zh-cn/web/api/htmlimageelement/srcset/index.md index 99d8dd2b95cf19..a87a5cc6675d70 100644 --- a/files/zh-cn/web/api/htmlimageelement/srcset/index.md +++ b/files/zh-cn/web/api/htmlimageelement/srcset/index.md @@ -57,9 +57,13 @@ let srcset = htmlImageElement.srcset; ```html
- Clock + Clock
``` diff --git a/files/zh-cn/web/api/htmlinputelement/index.md b/files/zh-cn/web/api/htmlinputelement/index.md index 4055ed41d9ec7d..ab00b81e703022 100644 --- a/files/zh-cn/web/api/htmlinputelement/index.md +++ b/files/zh-cn/web/api/htmlinputelement/index.md @@ -11,55 +11,55 @@ slug: Web/API/HTMLInputElement ## 属性 -| `form` {{readonlyInline}} | _`{{domxref("HTMLFormElement")}} object:`_ 返回一个父表单元素的引用。 | -| ------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `formAction` | _`string`:_ **返回/ 设置** 元素的 [`formaction`](/zh-CN/docs/Web/HTML/Element/input#formaction) 属性,包含处理元素提交信息程序的 URI. 这会重写父表单的 [`action`](/zh-CN/docs/Web/HTML/Element/form#action) 属性。 | -| `formEncType` | _`string`:_ **返回/ 设置** 元素的 [`formenctype`](/zh-CN/docs/Web/HTML/Element/input#formenctype) 属性,包含将表单提交到服务器的内容类型。这会重写父表单的 [`enctype`](/zh-CN/docs/Web/HTML/Element/form#enctype) 属性。 | -| `formMethod` | _`string`:_ **返回/ 设置** 元素的 [`formmethod`](/zh-CN/docs/Web/HTML/Element/input#formmethod) 属性,包含浏览器用于提交表单的 HTTP 方法。这会重写父表单的 [`method`](/zh-CN/docs/Web/HTML/Element/form#method) 属性。 | -| `formNoValidate` | _`boolean`:_ **返回/ 设置** 元素的 [`formnovalidate`](/zh-CN/docs/Web/HTML/Element/input#formnovalidate) 属性,表示在表单提交时不对其进行验证。这会重写父表单的 [`novalidate`](/zh-CN/docs/Web/HTML/Element/form#novalidate) 属性。 | -| `formTarget` | _`string`:_ **返回/ 设置** 元素的 [`formtarget`](/zh-CN/docs/Web/HTML/Element/input#formtarget) 属性,包含一个名称或关键字,表示在提交表单后接收响应的显示位置。这会重写父表单的 [`target`](/zh-CN/docs/Web/HTML/Element/form#target) 属性。 | +| `form` {{readonlyInline}} | _`{{domxref("HTMLFormElement")}} object:`_ 返回一个父表单元素的引用。 | +| ------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `formAction` | _`string`:_ **返回/ 设置** 元素的 [`formaction`](/zh-CN/docs/Web/HTML/Element/input#formaction) 属性,包含处理元素提交信息程序的 URI. 这会重写父表单的 [`action`](/zh-CN/docs/Web/HTML/Element/form#action) 属性。 | +| `formEncType` | _`string`:_ **返回/ 设置** 元素的 [`formenctype`](/zh-CN/docs/Web/HTML/Element/input#formenctype) 属性,包含将表单提交到服务器的内容类型。这会重写父表单的 [`enctype`](/zh-CN/docs/Web/HTML/Element/form#enctype) 属性。 | +| `formMethod` | _`string`:_ **返回/ 设置** 元素的 [`formmethod`](/zh-CN/docs/Web/HTML/Element/input#formmethod) 属性,包含浏览器用于提交表单的 HTTP 方法。这会重写父表单的 [`method`](/zh-CN/docs/Web/HTML/Element/form#method) 属性。 | +| `formNoValidate` | _`boolean`:_ **返回/ 设置** 元素的 [`formnovalidate`](/zh-CN/docs/Web/HTML/Element/input#formnovalidate) 属性,表示在表单提交时不对其进行验证。这会重写父表单的 [`novalidate`](/zh-CN/docs/Web/HTML/Element/form#novalidate) 属性。 | +| `formTarget` | _`string`:_ **返回/ 设置** 元素的 [`formtarget`](/zh-CN/docs/Web/HTML/Element/input#formtarget) 属性,包含一个名称或关键字,表示在提交表单后接收响应的显示位置。这会重写父表单的 [`target`](/zh-CN/docs/Web/HTML/Element/form#target) 属性。 | -| `name` | _`string`:_ **返回/ 设置** 元素的 [`name`](/zh-CN/docs/Web/HTML/Element/input#name) 属性,包含其名称。 | -| -------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `type` | `string:` **返回/ 设置** 元素的 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性,包含其显示类型。查看 {{ HTMLElement("input") }} 的 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性可用值。 | -| `disabled` | _`boolean`:_ **返回/ 设置** 元素的 [`disabled`](/zh-CN/docs/Web/HTML/Element/input#disabled) 属性,表示是否禁用 {{ HTMLElement("input") }}. 该元素的值将不会被提交。也可以查看 [`readonly`](/zh-CN/docs/Web/HTML/Element/input#readonly) | -| `autofocus` | `boolean:` **返回/ 设置** 元素的 [`autofocus`](/zh-CN/docs/Web/HTML/Element/input#autofocus) 属性,指定的 {{ HTMLElement("input") }} 在页面加载时应当具有输入焦点,例如通过键入不同的控件。在文档中只有一个表单元素可以拥有 [`autofocus`](/zh-CN/docs/Web/HTML/Element/input#autofocus) 属性。如果 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性被设置为 `hidden` 则无效 (即不可为隐藏控件设置自动焦点). | -| `required` | _`boolean`:_ **返回/ 设置** 元素的 [`required`](/zh-CN/docs/Web/HTML/Element/input#required) 属性,表示用户必填项。 | -| `value` | `string:` **返回/ 设置** 当前控件的值。**提示:** 如果用户输入与预期不同,可能会返回空。 | -| `validity` {{readonlyInline}} | `{{domxref("ValidityState")}} object:` Returns the validity state that this element is in. | -| `validationMessage` {{readonlyInline}} | `string:` **Returns** a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ([`willvalidate`](/zh-CN/docs/Web/HTML/Element/input#willvalidate) is false), or it satisfies its constraints. | -| `willValidate` {{readonlyInline}} | _`{{jsxref("Boolean")}}:`_ **Indicates** whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation. | +| `name` | _`string`:_ **返回/ 设置** 元素的 [`name`](/zh-CN/docs/Web/HTML/Element/input#name) 属性,包含其名称。 | +| -------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` | `string:` **返回/ 设置** 元素的 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性,包含其显示类型。查看 {{ HTMLElement("input") }} 的 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性可用值。 | +| `disabled` | _`boolean`:_ **返回/ 设置** 元素的 [`disabled`](/zh-CN/docs/Web/HTML/Element/input#disabled) 属性,表示是否禁用 {{ HTMLElement("input") }}. 该元素的值将不会被提交。也可以查看 [`readonly`](/zh-CN/docs/Web/HTML/Element/input#readonly) | +| `autofocus` | `boolean:` **返回/ 设置** 元素的 [`autofocus`](/zh-CN/docs/Web/HTML/Element/input#autofocus) 属性,指定的 {{ HTMLElement("input") }} 在页面加载时应当具有输入焦点,例如通过键入不同的控件。在文档中只有一个表单元素可以拥有 [`autofocus`](/zh-CN/docs/Web/HTML/Element/input#autofocus) 属性。如果 [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性被设置为 `hidden` 则无效 (即不可为隐藏控件设置自动焦点). | +| `required` | _`boolean`:_ **返回/ 设置** 元素的 [`required`](/zh-CN/docs/Web/HTML/Element/input#required) 属性,表示用户必填项。 | +| `value` | `string:` **返回/ 设置** 当前控件的值。**提示:** 如果用户输入与预期不同,可能会返回空。 | +| `validity` {{readonlyInline}} | `{{domxref("ValidityState")}} object:` Returns the validity state that this element is in. | +| `validationMessage` {{readonlyInline}} | `string:` **Returns** a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation ([`willvalidate`](/zh-CN/docs/Web/HTML/Element/input#willvalidate) is false), or it satisfies its constraints. | +| `willValidate` {{readonlyInline}} | _`{{jsxref("Boolean")}}:`_ **Indicates** whether the element is a candidate for constraint validation. It is false if any conditions bar it from constraint validation. | -| `checked` | `boolean:` **返回/ 设置** 当前选中状态,当控件[`type`](/zh-CN/docs/Web/HTML/Element/input#type) 是 `checkbox` 或 `radio` 时。 | +| `checked` | `boolean:` **返回/ 设置** 当前选中状态,当控件[`type`](/zh-CN/docs/Web/HTML/Element/input#type) 是 `checkbox` 或 `radio` 时。 | | ---------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `defaultChecked` | _`boolean:`_ **返回/ 设置** the default state of a radio button or checkbox as originally specified in HTML that created this object. | | `indeterminate` | `boolean:` **indicates** that the checkbox is neither on nor off. Changes the appearance to resemble a third state. Does not affect the value of the **checked** 属性,and clicking the checkbox will set the value to false. | | `alt` | _`string`:_ **返回/ 设置** 元素的 [`alt`](/zh-CN/docs/Web/HTML/Element/input#alt) 属性,包含 alternative text to use when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image.` | -| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `height` | _`string`:_ **返回/ 设置** 元素的 [`height`](/zh-CN/docs/Web/HTML/Element/input#height) 属性,which defines the height of the image displayed for the button, if the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image`. | +| -------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `height` | _`string`:_ **返回/ 设置** 元素的 [`height`](/zh-CN/docs/Web/HTML/Element/input#height) 属性,which defines the height of the image displayed for the button, if the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image`. | | `src` | `string:` **返回/ 设置** 元素的 [`src`](/zh-CN/docs/Web/HTML/Element/input#src) 属性,which specifies a URI for the location of an image to display on the graphical submit button, if the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image`; otherwise it is ignored. | | `width` | `string:` **返回/ 设置** the document's [`width`](/zh-CN/docs/Web/HTML/Element/input#width) 属性,which defines the width of the image displayed for the button, if the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `image`. | -| `accept` | _`string`:_ **Returns / Sets** 元素的 [`accept`](/zh-CN/docs/Web/HTML/Element/input#accept) 属性,包含 comma-separated list of file types accepted by the server when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `file`. | -| ------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `allowdirs` {{non-standard_inline}} | boolean: Part of the non-standard Directory Upload API; **indicates** whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference. | -| `files` | **Returns/accepts** a {{domxref("FileList")}} object, which contains a list of {{domxref("File")}} objects representing the files selected for upload. | -| {{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}} | boolean: **Returns** the [`webkitdirectory`](/zh-CN/docs/Web/HTML/Element/input#webkitdirectory) 属性; if true, the file system picker interface only accepts directories instead of files. | -| {{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{Non-standard_inline}} | Array of {{domxref("FileSystemEntry")}} objects **describing** the currently-selected files or directories. | +| `accept` | _`string`:_ **Returns / Sets** 元素的 [`accept`](/zh-CN/docs/Web/HTML/Element/input#accept) 属性,包含 comma-separated list of file types accepted by the server when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `file`. | +| ------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `allowdirs` {{non-standard_inline}} | boolean: Part of the non-standard Directory Upload API; **indicates** whether or not to allow directories and files both to be selected in the file list. Implemented only in Firefox and is hidden behind a preference. | +| `files` | **Returns/accepts** a {{domxref("FileList")}} object, which contains a list of {{domxref("File")}} objects representing the files selected for upload. | +| {{domxref("HTMLInputElement.webkitdirectory", "webkitdirectory")}} {{Non-standard_inline}} | boolean: **Returns** the [`webkitdirectory`](/zh-CN/docs/Web/HTML/Element/input#webkitdirectory) 属性; if true, the file system picker interface only accepts directories instead of files. | +| {{domxref("HTMLInputElement.webkitEntries", "webkitEntries")}} {{Non-standard_inline}} | Array of {{domxref("FileSystemEntry")}} objects **describing** the currently-selected files or directories. | | `autocomplete` | _`string`:_ **返回/ 设置** 元素的 [`autocomplete`](/zh-CN/docs/Web/HTML/Element/input#autocomplete) 属性,indicating whether the value of the control can be automatically completed by the browser. Ignored if the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `hidden`, `checkbox`, `radio`, `file`, or a button type (`button`, `submit`, `reset`, `image`). Possible values are: "on": the browser can autocomplete the value using previously stored value "off": the user must explicity enter a value | -| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `maxLength` | _`long`:_ **返回/ 设置** 元素的 [`maxlength`](/zh-CN/docs/Web/HTML/Element/input#maxlength) 属性,包含 the **maximum length of characters** (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.) | -| `size` | _`unsigned long`:_ **返回/ 设置** 元素的 [`size`](/zh-CN/docs/Web/HTML/Element/input#size) 属性,包含 **size of the control**. This value is in pixels unless the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `text` or `password`, in which case, it is an integer number of characters. Applies only when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is set to `text`, `search`, `tel`, `url`, `email`, or `password`; otherwise it is ignored. | -| `pattern` | _`string`:_ **返回/ 设置** 元素的 [`pattern`](/zh-CN/docs/Web/HTML/Element/input#pattern) 属性,包含 a **regular expression** that the control's value is checked against. Use the [`title`](/zh-CN/docs/Web/HTML/Element/input#title) 属性 to describe the pattern to help the user. This 属性 applies when the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. | -| `placeholder` | _`string`:_ **返回/ 设置** 元素的 [`placeholder`](/zh-CN/docs/Web/HTML/Element/input#placeholder) 属性,包含 a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This 属性 applies when the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. | -| `readOnly` | _`boolean`:_ **返回/ 设置** 元素的 [`readonly`](/zh-CN/docs/Web/HTML/Element/input#readonly) 属性,indicating that the user cannot modify the value of the control. This is ignored if the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `hidden`, `range`, `color`, `checkbox`, `radio`, `file`, or a button type. | -| `min` | _`string`:_ **返回/ 设置** 元素的 [`min`](/zh-CN/docs/Web/HTML/Element/input#min) 属性,包含 the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ([`max`](/zh-CN/docs/Web/HTML/Element/input#max) 属性) value. | -| `max` | _`string`:_ **返回/ 设置** 元素的 [`max`](/zh-CN/docs/Web/HTML/Element/input#max) 属性,包含 the maximum (numeric or date-time) value for this item, which must not be less than its minimum (**min** 属性) value. | -| `selectionStart` | _`unsigned long`:_ **返回/ 设置** the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element. | -| `selectionEnd` | _`unsigned long`:_ **返回/ 设置** the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position. | -| `selectionDirection` | _`string`:_ **返回/ 设置** the direction in which selection occurred. Possible values are: `"forward"` if selection was performed in the start-to-end direction of the current locale, `"backward"` for the opposite direction, `"none"` if the direction is unknown." | +| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `maxLength` | _`long`:_ **返回/ 设置** 元素的 [`maxlength`](/zh-CN/docs/Web/HTML/Element/input#maxlength) 属性,包含 the **maximum length of characters** (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.) | +| `size` | _`unsigned long`:_ **返回/ 设置** 元素的 [`size`](/zh-CN/docs/Web/HTML/Element/input#size) 属性,包含 **size of the control**. This value is in pixels unless the value of [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is `text` or `password`, in which case, it is an integer number of characters. Applies only when [`type`](/zh-CN/docs/Web/HTML/Element/input#type) is set to `text`, `search`, `tel`, `url`, `email`, or `password`; otherwise it is ignored. | +| `pattern` | _`string`:_ **返回/ 设置** 元素的 [`pattern`](/zh-CN/docs/Web/HTML/Element/input#pattern) 属性,包含 a **regular expression** that the control's value is checked against. Use the [`title`](/zh-CN/docs/Web/HTML/Element/input#title) 属性 to describe the pattern to help the user. This 属性 applies when the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. | +| `placeholder` | _`string`:_ **返回/ 设置** 元素的 [`placeholder`](/zh-CN/docs/Web/HTML/Element/input#placeholder) 属性,包含 a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This 属性 applies when the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `text`, `search`, `tel`, `url` or `email`; otherwise it is ignored. | +| `readOnly` | _`boolean`:_ **返回/ 设置** 元素的 [`readonly`](/zh-CN/docs/Web/HTML/Element/input#readonly) 属性,indicating that the user cannot modify the value of the control. This is ignored if the value of the [`type`](/zh-CN/docs/Web/HTML/Element/input#type) 属性 is `hidden`, `range`, `color`, `checkbox`, `radio`, `file`, or a button type. | +| `min` | _`string`:_ **返回/ 设置** 元素的 [`min`](/zh-CN/docs/Web/HTML/Element/input#min) 属性,包含 the minimum (numeric or date-time) value for this item, which must not be greater than its maximum ([`max`](/zh-CN/docs/Web/HTML/Element/input#max) 属性) value. | +| `max` | _`string`:_ **返回/ 设置** 元素的 [`max`](/zh-CN/docs/Web/HTML/Element/input#max) 属性,包含 the maximum (numeric or date-time) value for this item, which must not be less than its minimum (**min** 属性) value. | +| `selectionStart` | _`unsigned long`:_ **返回/ 设置** the beginning index of the selected text. When nothing is selected, this returns the position of the text input cursor (caret) inside of the {{HTMLElement("input")}} element. | +| `selectionEnd` | _`unsigned long`:_ **返回/ 设置** the end index of the selected text. When there's no selection, this returns the offset of the character immediately following the current text input cursor position. | +| `selectionDirection` | _`string`:_ **返回/ 设置** the direction in which selection occurred. Possible values are: `"forward"` if selection was performed in the start-to-end direction of the current locale, `"backward"` for the opposite direction, `"none"` if the direction is unknown." |
diff --git a/files/zh-cn/web/api/htmlinputelement/invalid_event/index.md b/files/zh-cn/web/api/htmlinputelement/invalid_event/index.md index 286ee950e8a867..7c2de33d1b55b5 100644 --- a/files/zh-cn/web/api/htmlinputelement/invalid_event/index.md +++ b/files/zh-cn/web/api/htmlinputelement/invalid_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLInputElement: invalid event' +title: "HTMLInputElement: invalid event" slug: Web/API/HTMLInputElement/invalid_event --- @@ -41,22 +41,28 @@ slug: Web/API/HTMLInputElement/invalid_event ```html
    -
  • -
  • +
  • + +
  • +
-

+ +

``` ### JavaScript ```js -const input = document.querySelector('input') -const log = document.getElementById('log') +const input = document.querySelector("input"); +const log = document.getElementById("log"); -input.addEventListener('invalid', logValue) +input.addEventListener("invalid", logValue); function logValue(e) { - log.textContent += e.target.value + log.textContent += e.target.value; } ``` diff --git a/files/zh-cn/web/api/htmlinputelement/labels/index.md b/files/zh-cn/web/api/htmlinputelement/labels/index.md index 35d49a56887c1c..94603ed757e966 100644 --- a/files/zh-cn/web/api/htmlinputelement/labels/index.md +++ b/files/zh-cn/web/api/htmlinputelement/labels/index.md @@ -23,16 +23,16 @@ var labelElements = input.labels; ```html - + ``` ### JavaScript ```js -window.addEventListener("DOMContentLoaded", function() { +window.addEventListener("DOMContentLoaded", function () { const input = document.getElementById("test"); - for(var i = 0; i < input.labels.length; i++) { + for (var i = 0; i < input.labels.length; i++) { console.log(input.labels[i].textContent); // "Label 1" and "Label 2" } }); diff --git a/files/zh-cn/web/api/htmlinputelement/multiple/index.md b/files/zh-cn/web/api/htmlinputelement/multiple/index.md index ba8897b4935298..1ea0c5f5a2133e 100644 --- a/files/zh-cn/web/api/htmlinputelement/multiple/index.md +++ b/files/zh-cn/web/api/htmlinputelement/multiple/index.md @@ -11,15 +11,14 @@ slug: Web/API/HTMLInputElement/multiple ```js // fileInput is a -let fileInput = document.getElementById('myfileinput'); +let fileInput = document.getElementById("myfileinput"); if (fileInput.multiple == true) { - for (let i = 0; i < fileInput.files.length; i++) { // Loop fileInput.files } -// Only one file available + // Only one file available } else { let file = fileInput.files.item(0); } diff --git a/files/zh-cn/web/api/htmlinputelement/select/index.md b/files/zh-cn/web/api/htmlinputelement/select/index.md index 6f7c77d8df7a42..f0d39d38775ad2 100644 --- a/files/zh-cn/web/api/htmlinputelement/select/index.md +++ b/files/zh-cn/web/api/htmlinputelement/select/index.md @@ -20,7 +20,7 @@ element.select() HTML ```html - + ``` @@ -28,7 +28,7 @@ JavaScript ```js function selectText() { - const input = document.getElementById('text-box'); + const input = document.getElementById("text-box"); input.focus(); input.select(); } diff --git a/files/zh-cn/web/api/htmlinputelement/select_event/index.md b/files/zh-cn/web/api/htmlinputelement/select_event/index.md index 6cc3bc876d87d6..fe24a6d64f2551 100644 --- a/files/zh-cn/web/api/htmlinputelement/select_event/index.md +++ b/files/zh-cn/web/api/htmlinputelement/select_event/index.md @@ -42,8 +42,8 @@ slug: Web/API/HTMLInputElement/select_event ## 属性 -| Property | Type | Description | -| ------------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------- | +| Property | Type | Description | +| ------------------------------- | ------------------------------------------------ | --------------------------------------------------------------------------------------------- | | `target` {{readonlyInline}} | [`EventTarget`](/zh-CN/docs/Web/API/EventTarget) | The event target (the topmost target in the DOM tree). | | `type` {{readonlyInline}} | [`DOMString`](/zh-CN/docs/Web/API/DOMString) | The type of event. | | `bubbles` {{readonlyInline}} | [`Boolean`](/zh-CN/docs/Web/API/Boolean) | Whether the event normally bubbles or not. | @@ -56,7 +56,7 @@ slug: Web/API/HTMLInputElement/select_event ### HTML ```html - +

``` @@ -64,13 +64,16 @@ slug: Web/API/HTMLInputElement/select_event ```js function logSelection(event) { - const log = document.getElementById('log'); - const selection = event.target.value.substring(event.target.selectionStart, event.target.selectionEnd); + const log = document.getElementById("log"); + const selection = event.target.value.substring( + event.target.selectionStart, + event.target.selectionEnd, + ); log.textContent = `You selected: ${selection}`; } -const input = document.querySelector('input'); -input.addEventListener('select', logSelection); +const input = document.querySelector("input"); +input.addEventListener("select", logSelection); ``` ### 结果 diff --git a/files/zh-cn/web/api/htmlinputelement/selectionchange_event/index.md b/files/zh-cn/web/api/htmlinputelement/selectionchange_event/index.md index 3ada68f2ffb9a5..46a01b8382db4c 100644 --- a/files/zh-cn/web/api/htmlinputelement/selectionchange_event/index.md +++ b/files/zh-cn/web/api/htmlinputelement/selectionchange_event/index.md @@ -18,8 +18,8 @@ obj.onselectionchange = function; ```js var selection; -document.onselectionchange = function() { - console.log('New selection made'); +document.onselectionchange = function () { + console.log("New selection made"); selection = document.getSelection(); }; ``` diff --git a/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.md b/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.md index 9a69057df4f01d..c6875fee642790 100644 --- a/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.md +++ b/files/zh-cn/web/api/htmlinputelement/setselectionrange/index.md @@ -30,6 +30,7 @@ element.setSelectionRange(selectionStart, selectionEnd [, selectionDirection]); - `selectionEnd` - : 被选中的最后一个字符的 _下一个_ 位置索引。如果这个值比元素的 value 长度还大,则会被看作 value 最后一个位置的索引。 - `selectionDirection` {{optional_inline}} + - : 一个表示选择方向的字符串,可能的值有: - `"forward"` diff --git a/files/zh-cn/web/api/htmlinputelement/showpicker/index.md b/files/zh-cn/web/api/htmlinputelement/showpicker/index.md index a0ee83fbb9d8a7..3705e1681773c4 100644 --- a/files/zh-cn/web/api/htmlinputelement/showpicker/index.md +++ b/files/zh-cn/web/api/htmlinputelement/showpicker/index.md @@ -47,7 +47,7 @@ showPicker() 以下代码展示了如何检查 `showPicker()` 是否被支持: ```js -if ('showPicker' in HTMLInputElement.prototype) { +if ("showPicker" in HTMLInputElement.prototype) { // showPicker() is supported. } ``` @@ -118,16 +118,16 @@ document.querySelectorAll("button").forEach((button) => { 以下代码增加了一个事件监听器,当按钮被点击时,调用 `showPicker()`。 ```js - const button = document.querySelector("button"); - const browserInput = document.querySelector("input"); - - button.addEventListener("click", () => { - try { - browserInput.showPicker(); - } catch (error) { - // Fall back to another picker mechanism - } - }); +const button = document.querySelector("button"); +const browserInput = document.querySelector("input"); + +button.addEventListener("click", () => { + try { + browserInput.showPicker(); + } catch (error) { + // Fall back to another picker mechanism + } +}); ``` ### showPicker() 用于 autocomplete @@ -143,16 +143,16 @@ document.querySelectorAll("button").forEach((button) => { 以下代码展示了当按钮被点击时,input 展示的选择器。 ```js - const button = document.querySelector("button"); - const browserInput = document.querySelector("input"); - - button.addEventListener("click", () => { - try { - browserInput.showPicker(); - } catch (error) { - // Fall back to another picker mechanism - } - }); +const button = document.querySelector("button"); +const browserInput = document.querySelector("input"); + +button.addEventListener("click", () => { + try { + browserInput.showPicker(); + } catch (error) { + // Fall back to another picker mechanism + } +}); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlinputelement/webkitdirectory/index.md b/files/zh-cn/web/api/htmlinputelement/webkitdirectory/index.md index 4b36e14ddd6035..838da120def713 100644 --- a/files/zh-cn/web/api/htmlinputelement/webkitdirectory/index.md +++ b/files/zh-cn/web/api/htmlinputelement/webkitdirectory/index.md @@ -11,7 +11,7 @@ slug: Web/API/HTMLInputElement/webkitdirectory ## 语法 ```js - HTMLInputElement.webkitdirectory = boolValue +HTMLInputElement.webkitdirectory = boolValue; ``` ### 值 @@ -51,7 +51,7 @@ slug: Web/API/HTMLInputElement/webkitdirectory 如果用户选择了`PhotoAlbums`,则文件列表上将会包含上面列出的每个文件的{{domxref("File")}}对象,而不是文件目录。条目`PIC2343.jpg`的`webkitRelativePath`属性将会得到`PhotoAlbums/Birthdays/Don's 40th birthday/PIC2343.jpg`的值。即使{{domxref("FileList")}}是扁平的,这也使得知道层次结构成为可能。 -> **备注:** 在 *Chromium < 72* 里,`webkitRelativePath` 的行为表现有所不同。有关更多详细信息,请参见[此 bug](https://bugs.chromium.org/p/chromium/issues/detail?id=124187)。 +> **备注:** 在 _Chromium < 72_ 里,`webkitRelativePath` 的行为表现有所不同。有关更多详细信息,请参见[此 bug](https://bugs.chromium.org/p/chromium/issues/detail?id=124187)。 ## 示例 @@ -67,16 +67,20 @@ slug: Web/API/HTMLInputElement/webkitdirectory ### JavaScript ```js -document.getElementById("filepicker").addEventListener("change", function(event) { - let output = document.getElementById("listing"); - let files = event.target.files; - - for (let i=0; i { +video.addEventListener("abort", () => { console.log(`Abort loading: ${videoSrc}`); }); -const source = document.createElement('source'); -source.setAttribute('src', videoSrc); -source.setAttribute('type', 'video/webm'); +const source = document.createElement("source"); +source.setAttribute("src", videoSrc); +source.setAttribute("type", "video/webm"); video.appendChild(source); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.md b/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.md index 7fab2809b00522..6f1d5d2062b42a 100644 --- a/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/audiotracks/index.md @@ -22,7 +22,7 @@ AudioTrackList 对象 表示音频/视频的可用音频轨道 以 audio 标签为例 ```html - + ``` 调用 diff --git a/files/zh-cn/web/api/htmlmediaelement/autoplay/index.md b/files/zh-cn/web/api/htmlmediaelement/autoplay/index.md index bd3937bf40fcb9..e686140402479f 100644 --- a/files/zh-cn/web/api/htmlmediaelement/autoplay/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/autoplay/index.md @@ -30,7 +30,7 @@ slug: Web/API/HTMLMediaElement/autoplay ... ```js -Xxx.xxx() +Xxx.xxx(); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.md b/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.md index ad115a56d08815..a4cac55caf6228 100644 --- a/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/canplay_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: canplay' +title: "HTMLMediaElement: canplay" slug: Web/API/HTMLMediaElement/canplay_event --- @@ -43,20 +43,20 @@ slug: Web/API/HTMLMediaElement/canplay_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('canplay', (event) => { - console.log('Video can start, but not sure it will play through.'); +video.addEventListener("canplay", (event) => { + console.log("Video can start, but not sure it will play through."); }); ``` 使用 `oncanplay` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.oncanplay = (event) => { - console.log('Video can start, but not sure it will play through.'); + console.log("Video can start, but not sure it will play through."); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.md b/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.md index 0e25e393bc46de..5cf1f64d496855 100644 --- a/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/canplaythrough_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: canplaythrough' +title: "HTMLMediaElement: canplaythrough" slug: Web/API/HTMLMediaElement/canplaythrough_event --- @@ -45,22 +45,26 @@ slug: Web/API/HTMLMediaElement/canplaythrough_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('canplaythrough', (event) => { - console.log('I think I can play through the entire ' + - 'video without ever having to stop to buffer.'); +video.addEventListener("canplaythrough", (event) => { + console.log( + "I think I can play through the entire " + + "video without ever having to stop to buffer.", + ); }); ``` 使用 `oncanplaythrough` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.oncanplaythrough = (event) => { - console.log('I think I can play through the entire ' + - 'video without ever having to stop to buffer.'); + console.log( + "I think I can play through the entire " + + "video without ever having to stop to buffer.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.md b/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.md index c5228b04b6823b..f72bead1eb4afb 100644 --- a/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/canplaytype/index.md @@ -33,8 +33,8 @@ str = audioOrVideo.canPlayType(mediaType); ## 示例 ```js -var obj = document.createElement('video'); -console.log(obj.canPlayType('video/mp4')); // "maybe" +var obj = document.createElement("video"); +console.log(obj.canPlayType("video/mp4")); // "maybe" ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlmediaelement/controls/index.md b/files/zh-cn/web/api/htmlmediaelement/controls/index.md index ea7f61d65e0d7b..be07c49f6d1690 100644 --- a/files/zh-cn/web/api/htmlmediaelement/controls/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/controls/index.md @@ -21,7 +21,7 @@ audio.controls = true; ## 例子 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); obj.controls = true; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.md b/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.md index e3ebca8b5b1bce..ec0e754770bdba 100644 --- a/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/currentsrc/index.md @@ -20,7 +20,7 @@ var mediaUrl = audioObject.currentSrc; ## 示例 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.currentSrc); // "" ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/currenttime/index.md b/files/zh-cn/web/api/htmlmediaelement/currenttime/index.md index 54a625631702d1..84cb0616d3cf17 100644 --- a/files/zh-cn/web/api/htmlmediaelement/currenttime/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/currenttime/index.md @@ -21,7 +21,7 @@ video.currentTime = 35; ## 示例 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.currentTime); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/duration/index.md b/files/zh-cn/web/api/htmlmediaelement/duration/index.md index dcc8705c8a091d..492ede5df1391c 100644 --- a/files/zh-cn/web/api/htmlmediaelement/duration/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/duration/index.md @@ -10,7 +10,7 @@ slug: Web/API/HTMLMediaElement/duration ## 语法 ```js -var myDuration = audioOrVideo.duration +var myDuration = audioOrVideo.duration; ``` ### 值 @@ -20,7 +20,7 @@ var myDuration = audioOrVideo.duration ## 例子 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.duration); // NaN ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.md b/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.md index 6e9fd38fb8517b..55f7839a8466de 100644 --- a/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/durationchange_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: durationchange 事件' +title: "HTMLMediaElement: durationchange 事件" slug: Web/API/HTMLMediaElement/durationchange_event --- @@ -54,20 +54,20 @@ slug: Web/API/HTMLMediaElement/durationchange_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('durationchange', (event) => { - console.log('Not sure why, but the duration of the video has changed.'); +video.addEventListener("durationchange", (event) => { + console.log("Not sure why, but the duration of the video has changed."); }); ``` 使用 `ondurationchange` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.ondurationchange = (event) => { - console.log('Not sure why, but the duration of the video has changed.'); + console.log("Not sure why, but the duration of the video has changed."); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/ended_event/index.md b/files/zh-cn/web/api/htmlmediaelement/ended_event/index.md index b18bb79c5d6d70..ea327e2f073488 100644 --- a/files/zh-cn/web/api/htmlmediaelement/ended_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/ended_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: ended 事件' +title: "HTMLMediaElement: ended 事件" slug: Web/API/HTMLMediaElement/ended_event --- @@ -47,22 +47,26 @@ slug: Web/API/HTMLMediaElement/ended_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('ended', (event) => { - console.log('Video stopped either because 1) it was over, ' + - 'or 2) no further data is available.'); +video.addEventListener("ended", (event) => { + console.log( + "Video stopped either because 1) it was over, " + + "or 2) no further data is available.", + ); }); ``` 使用 `onended` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onended = (event) => { - console.log('Video stopped either because 1) it was over, ' + - 'or 2) no further data is available.'); + console.log( + "Video stopped either because 1) it was over, " + + "or 2) no further data is available.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/error_event/index.md b/files/zh-cn/web/api/htmlmediaelement/error_event/index.md index fdabe9829df19b..4acc88e949c4bf 100644 --- a/files/zh-cn/web/api/htmlmediaelement/error_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/error_event/index.md @@ -14,9 +14,9 @@ slug: Web/API/HTMLMediaElement/error_event 在类似 {{domxref("EventTarget.addEventListener", "addEventListener()")}} 这样的方法中使用事件名称,或设置事件处理器属性。 ```js -addEventListener('error', (event) => {}); +addEventListener("error", (event) => {}); -onerror = (event) => { }; +onerror = (event) => {}; ``` ## 事件类型 @@ -26,14 +26,14 @@ onerror = (event) => { }; ## 示例 ```js -const video = document.querySelector('video'); -const videoSrc = 'https://path/to/video.webm'; +const video = document.querySelector("video"); +const videoSrc = "https://path/to/video.webm"; -video.addEventListener('error', () => { +video.addEventListener("error", () => { console.error(`Error loading: ${videoSrc}`); }); -video.setAttribute('src', videoSrc); +video.setAttribute("src", videoSrc); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.md b/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.md index 78d85d27a34a2f..5532be20856805 100644 --- a/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/loadeddata_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: loadeddata' +title: "HTMLMediaElement: loadeddata" slug: Web/API/HTMLMediaElement/loadeddata_event --- @@ -47,22 +47,26 @@ slug: Web/API/HTMLMediaElement/loadeddata_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('loadeddata', (event) => { - console.log('Yay! readyState just increased to ' + - 'HAVE_CURRENT_DATA or greater for first time.'); +video.addEventListener("loadeddata", (event) => { + console.log( + "Yay! readyState just increased to " + + "HAVE_CURRENT_DATA or greater for first time.", + ); }); ``` 使用 `onloadeddata` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onloadeddata = (event) => { - console.log('Yay! readyState just increased to ' + - 'HAVE_CURRENT_DATA or greater for first time.'); + console.log( + "Yay! readyState just increased to " + + "HAVE_CURRENT_DATA or greater for first time.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.md b/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.md index 2186f8ea6eb54b..9588f5de99b4c4 100644 --- a/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/loadstart_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: loadstart event' +title: "HTMLMediaElement: loadstart event" slug: Web/API/HTMLMediaElement/loadstart_event --- @@ -38,15 +38,13 @@ slug: Web/API/HTMLMediaElement/loadstart_event ```html
+ + - - - -
- - -
- +
+ + +
``` @@ -55,21 +53,21 @@ slug: Web/API/HTMLMediaElement/loadstart_event width: 18rem; height: 5rem; border: 1px solid black; - margin: .2rem; - padding: .2rem; + margin: 0.2rem; + padding: 0.2rem; } .example { display: grid; grid-template-areas: - "button log" - "video log"; + "button log" + "video log"; } button { grid-area: button; width: 10rem; - margin: .5rem 0; + margin: 0.5rem 0; } video { @@ -80,7 +78,7 @@ video { grid-area: log; } -.event-log>label { +.event-log > label { display: block; } ``` @@ -88,32 +86,34 @@ video { #### JS ```js -const loadVideo = document.querySelector('button'); -const video = document.querySelector('video'); -const eventLog = document.querySelector('.event-log-contents'); +const loadVideo = document.querySelector("button"); +const video = document.querySelector("video"); +const eventLog = document.querySelector(".event-log-contents"); let source = null; function handleEvent(event) { - eventLog.textContent = eventLog.textContent + `${event.type}\n`; + eventLog.textContent = eventLog.textContent + `${event.type}\n`; } -video.addEventListener('loadstart', handleEvent); -video.addEventListener('progress', handleEvent); -video.addEventListener('canplay', handleEvent); -video.addEventListener('canplaythrough', handleEvent); - -loadVideo.addEventListener('click', () => { - - if (source) { - document.location.reload(); - } else { - loadVideo.textContent = "Reset example"; - source = document.createElement('source'); - source.setAttribute('src', 'https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm'); - source.setAttribute('type', 'video/webm'); - - video.appendChild(source); - } +video.addEventListener("loadstart", handleEvent); +video.addEventListener("progress", handleEvent); +video.addEventListener("canplay", handleEvent); +video.addEventListener("canplaythrough", handleEvent); + +loadVideo.addEventListener("click", () => { + if (source) { + document.location.reload(); + } else { + loadVideo.textContent = "Reset example"; + source = document.createElement("source"); + source.setAttribute( + "src", + "https://interactive-examples.mdn.mozilla.net/media/examples/flower.webm", + ); + source.setAttribute("type", "video/webm"); + + video.appendChild(source); + } }); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/loop/index.md b/files/zh-cn/web/api/htmlmediaelement/loop/index.md index 2056debcdb669e..91f03be32054fb 100644 --- a/files/zh-cn/web/api/htmlmediaelement/loop/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/loop/index.md @@ -21,7 +21,7 @@ audio.loop = true; ## 示例 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); obj.loop = true; // true ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/muted/index.md b/files/zh-cn/web/api/htmlmediaelement/muted/index.md index bb18b3f113b95e..51a12d18d38d2e 100644 --- a/files/zh-cn/web/api/htmlmediaelement/muted/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/muted/index.md @@ -21,7 +21,7 @@ A {{domxref("Boolean")}}. `true` 表示被静音, `false` 表示未被静音 ## Example ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.muted); // false ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/networkstate/index.md b/files/zh-cn/web/api/htmlmediaelement/networkstate/index.md index bc9d52d9c13b47..643f661bb9d11a 100644 --- a/files/zh-cn/web/api/htmlmediaelement/networkstate/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/networkstate/index.md @@ -30,19 +30,17 @@ var networkState = audioOrVideo.networkState; ```html ``` ```js -var obj = document.getElementById('example'); - -obj.addEventListener('playing', function() { +var obj = document.getElementById("example"); +obj.addEventListener("playing", function () { if (obj.networkState === 2) { // Still loading... } - }); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/pause_event/index.md b/files/zh-cn/web/api/htmlmediaelement/pause_event/index.md index 49f44c6cf673c9..1cd847a16896e6 100644 --- a/files/zh-cn/web/api/htmlmediaelement/pause_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/pause_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: pause event' +title: "HTMLMediaElement: pause event" slug: Web/API/HTMLMediaElement/pause_event --- @@ -54,22 +54,26 @@ slug: Web/API/HTMLMediaElement/pause_event 使用 `addEventListener():` ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('pause', (event) => { - console.log('The Boolean paused property is now true. Either the ' + - 'pause() method was called or the autoplay attribute was toggled.'); +video.addEventListener("pause", (event) => { + console.log( + "The Boolean paused property is now true. Either the " + + "pause() method was called or the autoplay attribute was toggled.", + ); }); ``` 使用 `onpause` 事件监听属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onpause = (event) => { - console.log('The Boolean paused property is now true. Either the ' + - 'pause() method was called or the autoplay attribute was toggled.'); + console.log( + "The Boolean paused property is now true. Either the " + + "pause() method was called or the autoplay attribute was toggled.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/paused/index.md b/files/zh-cn/web/api/htmlmediaelement/paused/index.md index f08a74978e68b4..e2d78ffdba03dd 100644 --- a/files/zh-cn/web/api/htmlmediaelement/paused/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/paused/index.md @@ -22,7 +22,7 @@ _仅限暂停状态 因网络原因造成的缓冲状态仍然会告诉你不在 ## 例子 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.paused); // true ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/play_event/index.md b/files/zh-cn/web/api/htmlmediaelement/play_event/index.md index da37bc0739fda6..ce55c513052289 100644 --- a/files/zh-cn/web/api/htmlmediaelement/play_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/play_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: play event' +title: "HTMLMediaElement: play event" slug: Web/API/HTMLMediaElement/play_event --- @@ -52,22 +52,26 @@ slug: Web/API/HTMLMediaElement/play_event Using `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('play', (event) => { - console.log('The Boolean paused property is now false. Either the ' + - 'play() method was called or the autoplay attribute was toggled.'); +video.addEventListener("play", (event) => { + console.log( + "The Boolean paused property is now false. Either the " + + "play() method was called or the autoplay attribute was toggled.", + ); }); ``` Using the `onplay` event handler property: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onplay = (event) => { - console.log('The Boolean paused property is now false. Either the ' + - 'play() method was called or the autoplay attribute was toggled.'); + console.log( + "The Boolean paused property is now false. Either the " + + "play() method was called or the autoplay attribute was toggled.", + ); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.md b/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.md index 02564b9b408542..2c2e734f7d360d 100644 --- a/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/playbackrate/index.md @@ -29,7 +29,7 @@ audio.playbackRate = 1.0; ## 示例 ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.playbackRate); // 1 ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/playing_event/index.md b/files/zh-cn/web/api/htmlmediaelement/playing_event/index.md index 9a788240146b02..dafd6524823274 100644 --- a/files/zh-cn/web/api/htmlmediaelement/playing_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/playing_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: playing' +title: "HTMLMediaElement: playing" slug: Web/API/HTMLMediaElement/playing_event --- @@ -43,20 +43,20 @@ slug: Web/API/HTMLMediaElement/playing_event 使用 `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('playing', (event) => { - console.log('Video is no longer paused'); +video.addEventListener("playing", (event) => { + console.log("Video is no longer paused"); }); ``` 使用 `onplaying` 事件处理器属性: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.onplaying = (event) => { - console.log('Video is no longer paused.'); + console.log("Video is no longer paused."); }; ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/progress_event/index.md b/files/zh-cn/web/api/htmlmediaelement/progress_event/index.md index 0e55bea97c0a83..eccfba726c44ed 100644 --- a/files/zh-cn/web/api/htmlmediaelement/progress_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/progress_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: progress event' +title: "HTMLMediaElement: progress event" slug: Web/API/HTMLMediaElement/progress_event --- @@ -34,15 +34,13 @@ slug: Web/API/HTMLMediaElement/progress_event ```html
+ + - - - -
- - -
- +
+ + +
``` @@ -51,21 +49,21 @@ slug: Web/API/HTMLMediaElement/progress_event width: 18rem; height: 5rem; border: 1px solid black; - margin: .2rem; - padding: .2rem; + margin: 0.2rem; + padding: 0.2rem; } .example { display: grid; grid-template-areas: - "button log" - "video log"; + "button log" + "video log"; } button { grid-area: button; width: 10rem; - margin: .5rem 0; + margin: 0.5rem 0; } video { @@ -76,7 +74,7 @@ video { grid-area: log; } -.event-log>label { +.event-log > label { display: block; } ``` @@ -84,32 +82,34 @@ video { ### JavaScript ```js -const loadVideo = document.querySelector('button'); -const video = document.querySelector('video'); -const eventLog = document.querySelector('.event-log-contents'); +const loadVideo = document.querySelector("button"); +const video = document.querySelector("video"); +const eventLog = document.querySelector(".event-log-contents"); let source = null; function handleEvent(event) { - eventLog.textContent = eventLog.textContent + `${event.type}\n`; + eventLog.textContent = eventLog.textContent + `${event.type}\n`; } -video.addEventListener('loadstart', handleEvent); -video.addEventListener('progress', handleEvent); -video.addEventListener('canplay', handleEvent); -video.addEventListener('canplaythrough', handleEvent); - -loadVideo.addEventListener('click', () => { - - if (source) { - document.location.reload(); - } else { - loadVideo.textContent = "Reset example"; - source = document.createElement('source'); - source.setAttribute('src', 'https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4'); - source.setAttribute('type', 'video/mp4'); - - video.appendChild(source); - } +video.addEventListener("loadstart", handleEvent); +video.addEventListener("progress", handleEvent); +video.addEventListener("canplay", handleEvent); +video.addEventListener("canplaythrough", handleEvent); + +loadVideo.addEventListener("click", () => { + if (source) { + document.location.reload(); + } else { + loadVideo.textContent = "Reset example"; + source = document.createElement("source"); + source.setAttribute( + "src", + "https://mdn.github.io/learning-area/html/multimedia-and-embedding/video-and-audio-content/rabbit320.mp4", + ); + source.setAttribute("type", "video/mp4"); + + video.appendChild(source); + } }); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/readystate/index.md b/files/zh-cn/web/api/htmlmediaelement/readystate/index.md index 67f8846ccf9f6c..3e8490dc12cc87 100644 --- a/files/zh-cn/web/api/htmlmediaelement/readystate/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/readystate/index.md @@ -31,19 +31,17 @@ var readyState = audioOrVideo.readyState; ```html ``` ```js -var obj = document.getElementById('example'); +var obj = document.getElementById("example"); -obj.addEventListener('loadeddata', function() { - - if(obj.readyState >= 2) { +obj.addEventListener("loadeddata", function () { + if (obj.readyState >= 2) { obj.play(); } - }); ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/seekable/index.md b/files/zh-cn/web/api/htmlmediaelement/seekable/index.md index 5856ccdc730a5c..8f403bc772cd04 100644 --- a/files/zh-cn/web/api/htmlmediaelement/seekable/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/seekable/index.md @@ -19,13 +19,13 @@ var seekable = audioOrVideo.seekable; ## 示例 -```html +```js var video = document.querySelector("video"); var timeRangesObject = video.seekable; var timeRanges = []; //遍历所有时间区域并输出数组 for (let count = 0; count < timeRangesObject.length; count ++) { - timeRanges.push([timeRangesObject.start(count), timeRangesObject.end(count)]); + timeRanges.push([timeRangesObject.start(count), timeRangesObject.end(count)]); } ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/src/index.md b/files/zh-cn/web/api/htmlmediaelement/src/index.md index 97b1bfd114bff8..e9b4384b7356d6 100644 --- a/files/zh-cn/web/api/htmlmediaelement/src/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/src/index.md @@ -20,7 +20,7 @@ var mediaUrl = HTMLMediaElement.src; ## Example ```js -var obj = document.createElement('video'); +var obj = document.createElement("video"); console.log(obj.src); // "" ``` diff --git a/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.md b/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.md index 6bdcdb951bf774..9f2a62c7ea9e68 100644 --- a/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.md +++ b/files/zh-cn/web/api/htmlmediaelement/timeupdate_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLMediaElement: timeupdate' +title: "HTMLMediaElement: timeupdate" slug: Web/API/HTMLMediaElement/timeupdate_event --- @@ -56,20 +56,20 @@ These examples add an event listener for the HTMLMediaElement's `timeupdate` eve Using `addEventListener()`: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); -video.addEventListener('timeupdate', (event) => { - console.log('The currentTime attribute has been updated. Again.'); +video.addEventListener("timeupdate", (event) => { + console.log("The currentTime attribute has been updated. Again."); }); ``` Using the `ontimeupdate` event handler property: ```js -const video = document.querySelector('video'); +const video = document.querySelector("video"); video.ontimeupdate = (event) => { - console.log('The currentTime attribute has been updated. Again.'); + console.log("The currentTime attribute has been updated. Again."); }; ``` diff --git a/files/zh-cn/web/api/htmloptionelement/index.md b/files/zh-cn/web/api/htmloptionelement/index.md index bf13ab5f93b787..ad0c9a77530553 100644 --- a/files/zh-cn/web/api/htmloptionelement/index.md +++ b/files/zh-cn/web/api/htmloptionelement/index.md @@ -13,16 +13,16 @@ slug: Web/API/HTMLOptionElement _继承自其父类属性,{{domxref("HTMLElement")}}._ -| 名称 | 类型 | 描述 | -| ------------------------------- | ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `defaultSelected` | {{domxref("Boolean")}} | 包含了[`selected`](/zh-CN/docs/Web/HTML/Element/option#selected) HTML 特性的初始值,指示默认情况下是否选择该选项。 | -| `disabled` | {{domxref("Boolean")}} | 反映了[`disabled`](/zh-CN/docs/Web/HTML/Element/option#disabled) HTML 特性 的值 , 这意味着选项(option)是不可选的。如果一个选项是关闭的{{HTMLElement("optgroup")}}元素的子元素,那么它也可被关闭。 | -| `form`{{readonlyInline}} | {{domxref("HTMLFormElement")}} | 如果该选项是{{HTMLElement("select")}} 元素的后代,则该属性与相应{{DomXref("HTMLSelectElement")}} 对象的`form`属性具有相同的值; 否则为`null`。 | -| `index`{{readonlyInline}} | `long` | 该选项在其所属的选项列表中的位置,以树形顺序排列。如果该选项不是选项列表的一部分,例如为 {{HTMLElement("datalist")}} 元素的一部分时,该值为`0`。 | -| `label` | {{domxref("DOMString")}} | 反映[`label`](/zh-CN/docs/Web/HTML/Element/option#label) HTML 特性的值,该属性为选项提供了一个标签。如果没有特别设置此属性,读取它返回元素的文本内容。 | -| `selected` | {{domxref("Boolean")}} | 表示当前该 option 是否被选择。 | -| `text` | {{domxref("DOMString")}} | 包含元素的文本内容。 | -| `value` | {{domxref("DOMString")}} | 反映[`value`](/zh-CN/docs/Web/HTML/Element/option#value) HTML 特性的值(如果存在);否则反映{{domxref("Node.textContent")}} 特性的值。 | +| 名称 | 类型 | 描述 | +| ------------------------- | ------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `defaultSelected` | {{domxref("Boolean")}} | 包含了[`selected`](/zh-CN/docs/Web/HTML/Element/option#selected) HTML 特性的初始值,指示默认情况下是否选择该选项。 | +| `disabled` | {{domxref("Boolean")}} | 反映了[`disabled`](/zh-CN/docs/Web/HTML/Element/option#disabled) HTML 特性 的值 , 这意味着选项(option)是不可选的。如果一个选项是关闭的{{HTMLElement("optgroup")}}元素的子元素,那么它也可被关闭。 | +| `form`{{readonlyInline}} | {{domxref("HTMLFormElement")}} | 如果该选项是{{HTMLElement("select")}} 元素的后代,则该属性与相应{{DomXref("HTMLSelectElement")}} 对象的`form`属性具有相同的值; 否则为`null`。 | +| `index`{{readonlyInline}} | `long` | 该选项在其所属的选项列表中的位置,以树形顺序排列。如果该选项不是选项列表的一部分,例如为 {{HTMLElement("datalist")}} 元素的一部分时,该值为`0`。 | +| `label` | {{domxref("DOMString")}} | 反映[`label`](/zh-CN/docs/Web/HTML/Element/option#label) HTML 特性的值,该属性为选项提供了一个标签。如果没有特别设置此属性,读取它返回元素的文本内容。 | +| `selected` | {{domxref("Boolean")}} | 表示当前该 option 是否被选择。 | +| `text` | {{domxref("DOMString")}} | 包含元素的文本内容。 | +| `value` | {{domxref("DOMString")}} | 反映[`value`](/zh-CN/docs/Web/HTML/Element/option#value) HTML 特性的值(如果存在);否则反映{{domxref("Node.textContent")}} 特性的值。 | ## 方法 diff --git a/files/zh-cn/web/api/htmlscriptelement/index.md b/files/zh-cn/web/api/htmlscriptelement/index.md index a42696f98271ef..8dd92e5ec91a04 100644 --- a/files/zh-cn/web/api/htmlscriptelement/index.md +++ b/files/zh-cn/web/api/htmlscriptelement/index.md @@ -128,16 +128,21 @@ _没有具体的方法;属性从其父类继承,{{domxref("HTMLElement")}}。_ 让我们创建一个名为 importScript 的函数,它能够在一个文档中导入新的脚本,创建一个{{HTMLElement("script")}} 节点,并立即插入到宿主{{HTMLElement("script")}} 之前 (通过 {{domxref("document.currentScript")}} 可以获取宿主 script 标签)。这些脚本将**异步**执行。更多细节,请参见 defer 和 async 属性。 ```js -function loadError (oError) { +function loadError(oError) { throw new URIError("The script " + oError.target.src + " is not accessible."); } -function importScript (sSrc, fOnload) { +function importScript(sSrc, fOnload) { var oScript = document.createElement("script"); - oScript.type = "text\/javascript"; + oScript.type = "text/javascript"; oScript.onerror = loadError; - if (fOnload) { oScript.onload = fOnload; } - document.currentScript.parentNode.insertBefore(oScript, document.currentScript); + if (fOnload) { + oScript.onload = fOnload; + } + document.currentScript.parentNode.insertBefore( + oScript, + document.currentScript, + ); oScript.src = sSrc; } ``` @@ -148,20 +153,22 @@ function importScript (sSrc, fOnload) { ```js var importScript = (function (oHead) { - - function loadError (oError) { - throw new URIError("The script " + oError.target.src + " is not accessible."); + function loadError(oError) { + throw new URIError( + "The script " + oError.target.src + " is not accessible.", + ); } return function (sSrc, fOnload) { var oScript = document.createElement("script"); - oScript.type = "text\/javascript"; + oScript.type = "text/javascript"; oScript.onerror = loadError; - if (fOnload) { oScript.onload = fOnload; } + if (fOnload) { + oScript.onload = fOnload; + } oHead.appendChild(oScript); oScript.src = sSrc; - } - + }; })(document.head || document.getElementsByTagName("head")[0]); ``` @@ -169,7 +176,14 @@ var importScript = (function (oHead) { ```js importScript("myScript1.js"); -importScript("myScript2.js", /* onload function: */ function () { alert("You read this alert because the script \"myScript2.js\" has been correctly loaded."); }); +importScript( + "myScript2.js", + /* onload function: */ function () { + alert( + 'You read this alert because the script "myScript2.js" has been correctly loaded.', + ); + }, +); ``` ## 规范 diff --git a/files/zh-cn/web/api/htmlselectelement/index.md b/files/zh-cn/web/api/htmlselectelement/index.md index 4ecce05fdf5b8d..05b2f2f8f15d7f 100644 --- a/files/zh-cn/web/api/htmlselectelement/index.md +++ b/files/zh-cn/web/api/htmlselectelement/index.md @@ -91,13 +91,13 @@ _这个接口从 {{domxref("HTMLElement")}},{{domxref("Element")}} 和 {{domxr */ -var select = document.getElementById('s'); +var select = document.getElementById("s"); // return the index of the selected option console.log(select.selectedIndex); // 1 // return the value of the selected option -console.log(select.options[select.selectedIndex].value) // Second +console.log(select.options[select.selectedIndex].value); // Second ``` A better way to track changes to the user's selection is to watch for the {{domxref("HTMLElement/change_event", "change")}} event to occur on the ` - - - + + + + + + + + + + + +
NameOccupation
BobPlumber
JimRoofer
NameOccupation
BobPlumber
JimRoofer
``` ### JavaScript ```js -let table = document.querySelector('table'); +let table = document.querySelector("table"); table.deleteTHead(); ``` diff --git a/files/zh-cn/web/api/htmltableelement/rows/index.md b/files/zh-cn/web/api/htmltableelement/rows/index.md index 324f026ce1eb48..88c80edcdbe6a9 100644 --- a/files/zh-cn/web/api/htmltableelement/rows/index.md +++ b/files/zh-cn/web/api/htmltableelement/rows/index.md @@ -20,7 +20,7 @@ HTMLCollectionObject = table.rows ```js myrows = mytable.rows; firstRow = mytable.rows[0]; -lastRow = mytable.rows[mytable.rows.length-1]; +lastRow = mytable.rows[mytable.rows.length - 1]; ``` ## Specification diff --git a/files/zh-cn/web/api/htmltablerowelement/rowindex/index.md b/files/zh-cn/web/api/htmltablerowelement/rowindex/index.md index 191d1b13dc540f..7ba50aa5e1e578 100644 --- a/files/zh-cn/web/api/htmltablerowelement/rowindex/index.md +++ b/files/zh-cn/web/api/htmltablerowelement/rowindex/index.md @@ -12,7 +12,7 @@ slug: Web/API/HTMLTableRowElement/rowIndex ## 语法 ```js -var index = HTMLTableRowElement.rowIndex +var index = HTMLTableRowElement.rowIndex; ``` ### 返回值 @@ -28,15 +28,30 @@ var index = HTMLTableRowElement.rowIndex ```html - + + + + - - - + + + + + + + + + + + + - + + + +
商品 价格
商品价格
香蕉 $2
橘子 $8
西冷牛排 $20
香蕉$2
橘子$8
西冷牛排$20
总计 $30
总计$30
``` @@ -44,7 +59,7 @@ var index = HTMLTableRowElement.rowIndex ### JavaScript ```js -let rows = document.querySelectorAll('tr'); +let rows = document.querySelectorAll("tr"); rows.forEach((row) => { let z = document.createElement("td"); diff --git a/files/zh-cn/web/api/htmltextareaelement/index.md b/files/zh-cn/web/api/htmltextareaelement/index.md index c0027a8cf56f5e..182d2f6e5380a7 100644 --- a/files/zh-cn/web/api/htmltextareaelement/index.md +++ b/files/zh-cn/web/api/htmltextareaelement/index.md @@ -11,49 +11,49 @@ slug: Web/API/HTMLTextAreaElement ## 属性 -| `form` {{readonlyInline}} | `object:` 返回一个父表单元素的引用。如果这个元素没有被包含在一个表单元素中,则这个值是页面中任意一个 {{HTMLElement("form")}} 元素的 [`id`](/zh-CN/docs/Web/HTML/Element/form#id) 属性或者 `null`。 | -| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `type` {{readonlyInline}} | `string:` 返回字符串 `textarea`。 | -| `value` | `string:` Returns / Sets the raw value contained in the control. | -| `textLength` {{readonlyInline}} | `long:` Returns the codepoint length of the control's `value`. Same as `calling value.length` | -| `defaultValue` | `string:` Returns / Sets the control's default value, which behaves like the {{domxref("Node.textContent")}} property. | -| `placeholder` | `string:` 返回/设置元素[`placeholder`](/zh-CN/docs/Web/HTML/Element/textarea#placeholder) 属性,用于提示用户在组件中应该输入什么。 | -| `rows` | `unsigned long:` Returns / Sets the element's [`rows`](/zh-CN/docs/Web/HTML/Element/textarea#rows) attribute, indicating the number of visible text lines for the control. | -| `cols` | `unsigned long:` Returns / Sets the element's [`cols`](/zh-CN/docs/Web/HTML/Element/textarea#cols) attribute, indicating the visible width of the text area. | -| `autofocus` | `boolean:` Returns / Sets the element's [`autofocus`](/zh-CN/docs/Web/HTML/Element/textarea#autofocus) attribute, indicating that the control should have input focus when the page loads | -| `name` | `string:` Returns / Sets the element's [`name`](/zh-CN/docs/Web/HTML/Element/textarea#name) attribute, containing the name of the control. | -| `disabled` | `boolean:` Returns / Sets the element's [`disabled`](/zh-CN/docs/Web/HTML/Element/textarea#disabled) attribute, indicating that the control is not available for interaction. | -| {{domxref("HTMLTextAreaElement.labels")}}{{ReadOnlyInline}} | {{domxref("NodeList")}}: Returns a list of label elements associated with this select element. | -| `maxLength` | `long:` Returns / Sets the element's [`maxlength`](/zh-CN/docs/Web/HTML/Element/textarea#maxlength) attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes. | -| `minLength` | `long:` Returns / Sets the element's [`minlength`](/zh-CN/docs/Web/HTML/Element/textarea#minlength) attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes. | -| `accessKey` | `string:` Returns / Sets the element's [`accesskey`](/zh-CN/docs/Web/HTML/Element/textarea#accesskey) attribute. | -| `readOnly` | `boolean:` Returns / Sets the element's [`readonly`](/zh-CN/docs/Web/HTML/Element/textarea#readonly) attribute, indicating that the user cannot modify the value of the control. | -| `required` | `boolean:` Returns / Sets the element's [`required`](/zh-CN/docs/Web/HTML/Element/textarea#required) attribute, indicating that the user must specify a value before submitting the form. | -| `tabIndex` | `long:` Returns / Sets the position of the element in the tabbing navigation order for the current document. | -| `selectionStart` | `unsigned long:` Returns / Sets the index of the beginning of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the first argument, and `selectionEnd` as the second argument. | -| `selectionEnd` | `unsigned long:` Returns / Sets the index of the end of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the second argument, and `selectionStart` as the first argument. | -| `selectionDirection` | `string:` Returns / Sets the direction in which selection occurred. This is `"forward"` if selection was performed in the start-to-end direction of the current locale, or `"backward"` for the opposite direction. This can also be `"none"` if the direction is unknown." | -| `validity` {{readonlyInline}} | `{{domxref("ValidityState")}} object:` Returns the validity states that this element is in. | -| `willValidate` {{readonlyInline}} | `boolean:` Returns whether the element is a candidate for constraint validation. `false` if any conditions bar it from constraint validation, including its `readOnly` or `disabled` property is `true`. | -| `validationMessage` {{readonlyInline}} | `string:` Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints. | -| `autocomplete` {{experimental_inline}} | | -| `autocapitalize` {{experimental_inline}} | `string:` Returns / Sets the element's capitalization behavior for user input. Valid values are: `none`, `off`, `characters`, `words`, `sentences`. | -| `inputMode` {{experimental_inline}} | | -| `wrap` | `string:` Returns / Sets the [`wrap`](/zh-CN/docs/Web/HTML/Element/textarea#wrap) HTML attribute, indicating how the control wraps text. | +| `form` {{readonlyInline}} | `object:` 返回一个父表单元素的引用。如果这个元素没有被包含在一个表单元素中,则这个值是页面中任意一个 {{HTMLElement("form")}} 元素的 [`id`](/zh-CN/docs/Web/HTML/Element/form#id) 属性或者 `null`。 | +| ----------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `type` {{readonlyInline}} | `string:` 返回字符串 `textarea`。 | +| `value` | `string:` Returns / Sets the raw value contained in the control. | +| `textLength` {{readonlyInline}} | `long:` Returns the codepoint length of the control's `value`. Same as `calling value.length` | +| `defaultValue` | `string:` Returns / Sets the control's default value, which behaves like the {{domxref("Node.textContent")}} property. | +| `placeholder` | `string:` 返回/设置元素[`placeholder`](/zh-CN/docs/Web/HTML/Element/textarea#placeholder) 属性,用于提示用户在组件中应该输入什么。 | +| `rows` | `unsigned long:` Returns / Sets the element's [`rows`](/zh-CN/docs/Web/HTML/Element/textarea#rows) attribute, indicating the number of visible text lines for the control. | +| `cols` | `unsigned long:` Returns / Sets the element's [`cols`](/zh-CN/docs/Web/HTML/Element/textarea#cols) attribute, indicating the visible width of the text area. | +| `autofocus` | `boolean:` Returns / Sets the element's [`autofocus`](/zh-CN/docs/Web/HTML/Element/textarea#autofocus) attribute, indicating that the control should have input focus when the page loads | +| `name` | `string:` Returns / Sets the element's [`name`](/zh-CN/docs/Web/HTML/Element/textarea#name) attribute, containing the name of the control. | +| `disabled` | `boolean:` Returns / Sets the element's [`disabled`](/zh-CN/docs/Web/HTML/Element/textarea#disabled) attribute, indicating that the control is not available for interaction. | +| {{domxref("HTMLTextAreaElement.labels")}}{{ReadOnlyInline}} | {{domxref("NodeList")}}: Returns a list of label elements associated with this select element. | +| `maxLength` | `long:` Returns / Sets the element's [`maxlength`](/zh-CN/docs/Web/HTML/Element/textarea#maxlength) attribute, indicating the maximum number of characters the user can enter. This constraint is evaluated only when the value changes. | +| `minLength` | `long:` Returns / Sets the element's [`minlength`](/zh-CN/docs/Web/HTML/Element/textarea#minlength) attribute, indicating the minimum number of characters the user can enter. This constraint is evaluated only when the value changes. | +| `accessKey` | `string:` Returns / Sets the element's [`accesskey`](/zh-CN/docs/Web/HTML/Element/textarea#accesskey) attribute. | +| `readOnly` | `boolean:` Returns / Sets the element's [`readonly`](/zh-CN/docs/Web/HTML/Element/textarea#readonly) attribute, indicating that the user cannot modify the value of the control. | +| `required` | `boolean:` Returns / Sets the element's [`required`](/zh-CN/docs/Web/HTML/Element/textarea#required) attribute, indicating that the user must specify a value before submitting the form. | +| `tabIndex` | `long:` Returns / Sets the position of the element in the tabbing navigation order for the current document. | +| `selectionStart` | `unsigned long:` Returns / Sets the index of the beginning of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the first argument, and `selectionEnd` as the second argument. | +| `selectionEnd` | `unsigned long:` Returns / Sets the index of the end of selected text. If no text is selected, contains the index of the character that follows the input cursor. On being set, the control behaves as if `setSelectionRange()` had been called with this as the second argument, and `selectionStart` as the first argument. | +| `selectionDirection` | `string:` Returns / Sets the direction in which selection occurred. This is `"forward"` if selection was performed in the start-to-end direction of the current locale, or `"backward"` for the opposite direction. This can also be `"none"` if the direction is unknown." | +| `validity` {{readonlyInline}} | `{{domxref("ValidityState")}} object:` Returns the validity states that this element is in. | +| `willValidate` {{readonlyInline}} | `boolean:` Returns whether the element is a candidate for constraint validation. `false` if any conditions bar it from constraint validation, including its `readOnly` or `disabled` property is `true`. | +| `validationMessage` {{readonlyInline}} | `string:` Returns a localized message that describes the validation constraints that the control does not satisfy (if any). This is the empty string if the control is not a candidate for constraint validation (`willValidate` is `false`), or it satisfies its constraints. | +| `autocomplete` {{experimental_inline}} | | +| `autocapitalize` {{experimental_inline}} | `string:` Returns / Sets the element's capitalization behavior for user input. Valid values are: `none`, `off`, `characters`, `words`, `sentences`. | +| `inputMode` {{experimental_inline}} | | +| `wrap` | `string:` Returns / Sets the [`wrap`](/zh-CN/docs/Web/HTML/Element/textarea#wrap) HTML attribute, indicating how the control wraps text. | The two properties `tabIndex` and `accessKey` are inherited from {{domxref("HTMLElement")}} from HTML5 on, but were defined on `HTMLTextAreaElement` in DOM Level 2 HTML and earlier specifications. ## 方法 -| {{domxref("HTMLElement/blur", "blur()")}} | Removes focus from the control; keystrokes will subsequently go nowhere. | -| ------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| {{domxref("HTMLElement/focus", "focus()")}} | Gives focus to the control; keystrokes will subsequently go to this element. | -| {{domxref("HTMLInputElement/select", "select()")}} | Selects the contents of the control. | -| {{domxref("HTMLInputElement/setRangeText", "setRangeText()")}} | Replaces a range of text in the element with new text. | +| {{domxref("HTMLElement/blur", "blur()")}} | Removes focus from the control; keystrokes will subsequently go nowhere. | +| ------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| {{domxref("HTMLElement/focus", "focus()")}} | Gives focus to the control; keystrokes will subsequently go to this element. | +| {{domxref("HTMLInputElement/select", "select()")}} | Selects the contents of the control. | +| {{domxref("HTMLInputElement/setRangeText", "setRangeText()")}} | Replaces a range of text in the element with new text. | | {{domxref("HTMLInputElement/setSelectionRange", "setSelectionRange()")}} | Selects a range of text in the element (but does not focus it). | -| `checkValidity()` | Returns `false` if the button is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable `invalid` event at the control. It returns `true` if the control is not a candidate for constraint validation, or if it satisfies its constraints. | -| `reportValidity()` | This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable `invalid` event at the element, and returns `false`; if there are no problems, it returns `true`. | -| `setCustomValidity(DOMstring)` | Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. | +| `checkValidity()` | Returns `false` if the button is a candidate for constraint validation, and it does not satisfy its constraints. In this case, it also fires a cancelable `invalid` event at the control. It returns `true` if the control is not a candidate for constraint validation, or if it satisfies its constraints. | +| `reportValidity()` | This method reports the problems with the constraints on the element, if any, to the user. If there are problems, it fires a cancelable `invalid` event at the element, and returns `false`; if there are no problems, it returns `true`. | +| `setCustomValidity(DOMstring)` | Sets a custom validity message for the element. If this message is not the empty string, then the element is suffering from a custom validity error, and does not validate. | The two methods `blur()` and `focus()` are inherited from {{domxref("HTMLElement")}} from HTML5 on, but were defined on `HTMLTextAreaElement` in DOM Level 2 HTML and earlier specifications. @@ -73,7 +73,7 @@ Make a textarea autogrow while typing: JavaScript function: ```js -function autoGrow (oField) { +function autoGrow(oField) { if (oField.scrollHeight > oField.clientHeight) { oField.style.height = oField.scrollHeight + "px"; } @@ -111,9 +111,21 @@ JavaScript function: ```js function insertMetachars(sStartTag, sEndTag) { - var bDouble = arguments.length > 1, oMsgInput = document.myForm.myTxtArea, nSelStart = oMsgInput.selectionStart, nSelEnd = oMsgInput.selectionEnd, sOldText = oMsgInput.value; - oMsgInput.value = sOldText.substring(0, nSelStart) + (bDouble ? sStartTag + sOldText.substring(nSelStart, nSelEnd) + sEndTag : sStartTag) + sOldText.substring(nSelEnd); - oMsgInput.setSelectionRange(bDouble || nSelStart === nSelEnd ? nSelStart + sStartTag.length : nSelStart, (bDouble ? nSelEnd : nSelStart) + sStartTag.length); + var bDouble = arguments.length > 1, + oMsgInput = document.myForm.myTxtArea, + nSelStart = oMsgInput.selectionStart, + nSelEnd = oMsgInput.selectionEnd, + sOldText = oMsgInput.value; + oMsgInput.value = + sOldText.substring(0, nSelStart) + + (bDouble + ? sStartTag + sOldText.substring(nSelStart, nSelEnd) + sEndTag + : sStartTag) + + sOldText.substring(nSelEnd); + oMsgInput.setSelectionRange( + bDouble || nSelStart === nSelEnd ? nSelStart + sStartTag.length : nSelStart, + (bDouble ? nSelEnd : nSelStart) + sStartTag.length, + ); oMsgInput.focus(); } ``` @@ -132,8 +144,38 @@ HTML: ```html
-

Bold | Italic | URL | code | smile | etc. etc. ]

-

+

+ [ Bold + | + Italic + | + URL + | + code + | smile | + etc. etc. ] +

+

+ +

``` @@ -147,25 +189,43 @@ First, create a function that takes the text field and a key event as input and ```js function checkRows(oField, oKeyEvent) { - var nKey = (oKeyEvent || /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 }).keyCode, - + var nKey = ( + oKeyEvent || + /* old IE */ window.event || /* check is not supported! */ { keyCode: 38 } + ).keyCode, // put here the maximum number of characters per line: nCols = 30, // put here the maximum number of lines: nRows = 5, - - nSelS = oField.selectionStart, nSelE = oField.selectionEnd, - sVal = oField.value, nLen = sVal.length, - + nSelS = oField.selectionStart, + nSelE = oField.selectionEnd, + sVal = oField.value, + nLen = sVal.length, nBackward = nSelS >= nCols ? nSelS - nCols : 0, - nDeltaForw = sVal.substring(nBackward, nSelS).search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1, + nDeltaForw = + sVal + .substring(nBackward, nSelS) + .search(new RegExp("\\n(?!.{0," + String(nCols - 2) + "}\\n)")) + 1, nRowStart = nBackward + nDeltaForw, - aReturns = (sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length)).match(/\n/g), + aReturns = ( + sVal.substring(0, nSelS) + sVal.substring(nSelE, sVal.length) + ).match(/\n/g), nRowEnd = nSelE + nRowStart + nCols - nSelS, - sRow = sVal.substring(nRowStart, nSelS) + sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd), - bKeepCols = nKey === 13 || nLen + 1 < nCols || /\n/.test(sRow) || ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) && (sRow.length < nCols || (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n")))); - - return (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) && ((nKey > 32 && nKey < 41) || bKeepCols); + sRow = + sVal.substring(nRowStart, nSelS) + + sVal.substring(nSelE, nRowEnd > nLen ? nLen : nRowEnd), + bKeepCols = + nKey === 13 || + nLen + 1 < nCols || + /\n/.test(sRow) || + ((nRowStart === 0 || nDeltaForw > 0 || nKey > 0) && + (sRow.length < nCols || + (nKey > 0 && (nLen === nRowEnd || sVal.charAt(nRowEnd) === "\n")))); + + return ( + (nKey !== 13 || (aReturns ? aReturns.length + 1 : 1) < nRows) && + ((nKey > 32 && nKey < 41) || bKeepCols) + ); } ``` @@ -173,9 +233,13 @@ In the HTML we just need to hook our function to the `onkeypress` event and spec ```html
-

Textarea with fixed number of characters per line:
- +

+ Textarea with fixed number of characters per line:
+

``` diff --git a/files/zh-cn/web/api/htmlvideoelement/enterpictureinpicture_event/index.md b/files/zh-cn/web/api/htmlvideoelement/enterpictureinpicture_event/index.md index a553c62c6555e2..d2a7ae5bfd7ceb 100644 --- a/files/zh-cn/web/api/htmlvideoelement/enterpictureinpicture_event/index.md +++ b/files/zh-cn/web/api/htmlvideoelement/enterpictureinpicture_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLVideoElement: enterpictureinpicture event' +title: "HTMLVideoElement: enterpictureinpicture event" slug: Web/API/HTMLVideoElement/enterpictureinpicture_event --- @@ -14,9 +14,9 @@ slug: Web/API/HTMLVideoElement/enterpictureinpicture_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}}使用事件的名称,或者设置事件处理器属性。 ```js -addEventListener('enterpictureinpicture', event => { }); +addEventListener("enterpictureinpicture", (event) => {}); -onenterpictureinpicture = event => { }; +onenterpictureinpicture = (event) => {}; ``` ## 事件类型 diff --git a/files/zh-cn/web/api/htmlvideoelement/leavepictureinpicture_event/index.md b/files/zh-cn/web/api/htmlvideoelement/leavepictureinpicture_event/index.md index 1a37ea316ba2ed..a39e73e9c77297 100644 --- a/files/zh-cn/web/api/htmlvideoelement/leavepictureinpicture_event/index.md +++ b/files/zh-cn/web/api/htmlvideoelement/leavepictureinpicture_event/index.md @@ -1,5 +1,5 @@ --- -title: 'HTMLVideoElement: leavepictureinpicture event' +title: "HTMLVideoElement: leavepictureinpicture event" slug: Web/API/HTMLVideoElement/leavepictureinpicture_event --- @@ -14,9 +14,9 @@ slug: Web/API/HTMLVideoElement/leavepictureinpicture_event 在 {{domxref("EventTarget.addEventListener", "addEventListener()")}}等方法中使用事件方法名,或者设置事件处理器属性。 ```js -addEventListener('leavepictureinpicture', event => { }); +addEventListener("leavepictureinpicture", (event) => {}); -onleavepictureinpicture = event => { }; +onleavepictureinpicture = (event) => {}; ``` ## 事件类型 diff --git a/files/zh-cn/web/api/htmlvideoelement/requestpictureinpicture/index.md b/files/zh-cn/web/api/htmlvideoelement/requestpictureinpicture/index.md index d035eed9eb5753..2e11ef527d010b 100644 --- a/files/zh-cn/web/api/htmlvideoelement/requestpictureinpicture/index.md +++ b/files/zh-cn/web/api/htmlvideoelement/requestpictureinpicture/index.md @@ -5,13 +5,13 @@ slug: Web/API/HTMLVideoElement/requestPictureInPicture {{ APIRef("HTML DOM") }} - **{{domxref("HTMLVideoElement")}}** 接口提供的 **`requestPictureInPicture()`** 方法会发出异步请求,并以画中画的模式显示视频。 +**{{domxref("HTMLVideoElement")}}** 接口提供的 **`requestPictureInPicture()`** 方法会发出异步请求,并以画中画的模式显示视频。 该方法不能保证视频进入画中画。如果授予了进入画中画的权限,则将返回一个 {{jsxref("Promise")}},最终完成后将收到一个 {{domxref("HTMLVideoElement.enterpictureinpicture_event", "enterpictureinpicture")}} 事件,来表示它现在处于画中画状态。 ## 语法 -```js +```js-nolint requestPictureInPicture() ``` @@ -25,10 +25,13 @@ requestPictureInPicture() ```js function enterPictureInPicture() { - videoElement.requestPictureInPicture() - .then(pictureInPictureWindow => { - pictureInPictureWindow.addEventListener("resize", () => onPipWindowResize(), false); - }) + videoElement.requestPictureInPicture().then((pictureInPictureWindow) => { + pictureInPictureWindow.addEventListener( + "resize", + () => onPipWindowResize(), + false, + ); + }); } ``` diff --git a/files/zh-cn/web/api/htmlvideoelement/videoheight/index.md b/files/zh-cn/web/api/htmlvideoelement/videoheight/index.md index 544b133c4ec52a..c284a6d35b7980 100644 --- a/files/zh-cn/web/api/htmlvideoelement/videoheight/index.md +++ b/files/zh-cn/web/api/htmlvideoelement/videoheight/index.md @@ -34,15 +34,19 @@ slug: Web/API/HTMLVideoElement/videoHeight ```js let v = document.getElementById("myVideo"); -v.addEventListener("resize", ev => { - let w = v.videoWidth; - let h = v.videoHeight; - - if (w && h) { - v.style.width = w; - v.style.height = h; - } -}, false); +v.addEventListener( + "resize", + (ev) => { + let w = v.videoWidth; + let h = v.videoHeight; + + if (w && h) { + v.style.width = w; + v.style.height = h; + } + }, + false, +); ``` 请注意,只有当 `videoWidth` 和 `videoHeight` 都不是 0 的情况,才会应用更改。 diff --git a/files/zh-cn/web/api/idbcursor/direction/index.md b/files/zh-cn/web/api/idbcursor/direction/index.md index a9808968597f20..7e2fa4b558e508 100644 --- a/files/zh-cn/web/api/idbcursor/direction/index.md +++ b/files/zh-cn/web/api/idbcursor/direction/index.md @@ -38,24 +38,28 @@ prev ```js function backwards() { - list.innerHTML = ''; - var transaction = db.transaction(['rushAlbumList'], 'readonly'); - var objectStore = transaction.objectStore('rushAlbumList'); + list.innerHTML = ""; + var transaction = db.transaction(["rushAlbumList"], "readonly"); + var objectStore = transaction.objectStore("rushAlbumList"); - objectStore.openCursor(null,'prev').onsuccess = function(event) { + objectStore.openCursor(null, "prev").onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { - var listItem = document.createElement('li'); - listItem.innerHTML = '' + cursor.value.albumTitle + ', ' + cursor.value.year; - list.appendChild(listItem); - - console.log(cursor.direction); - cursor.continue(); - } else { - console.log('Entries displayed backwards.'); - } + if (cursor) { + var listItem = document.createElement("li"); + listItem.innerHTML = + "" + + cursor.value.albumTitle + + ", " + + cursor.value.year; + list.appendChild(listItem); + + console.log(cursor.direction); + cursor.continue(); + } else { + console.log("Entries displayed backwards."); + } }; -}; +} ``` ## Specifications diff --git a/files/zh-cn/web/api/idbcursor/index.md b/files/zh-cn/web/api/idbcursor/index.md index 7a384e7c94cb74..9d2377f256cb9f 100644 --- a/files/zh-cn/web/api/idbcursor/index.md +++ b/files/zh-cn/web/api/idbcursor/index.md @@ -50,22 +50,22 @@ slug: Web/API/IDBCursor ```js function displayData() { - var transaction = db.transaction(['rushAlbumList'], "readonly"); - var objectStore = transaction.objectStore('rushAlbumList'); + var transaction = db.transaction(["rushAlbumList"], "readonly"); + var objectStore = transaction.objectStore("rushAlbumList"); - objectStore.openCursor().onsuccess = function(event) { + objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { - var listItem = document.createElement('li'); - listItem.innerHTML = cursor.value.albumTitle + ', ' + cursor.value.year; + if (cursor) { + var listItem = document.createElement("li"); + listItem.innerHTML = cursor.value.albumTitle + ", " + cursor.value.year; list.appendChild(listItem); cursor.continue(); } else { - console.log('Entries all displayed.'); + console.log("Entries all displayed."); } }; -}; +} ``` ## Specifications diff --git a/files/zh-cn/web/api/idbdatabase/createobjectstore/index.md b/files/zh-cn/web/api/idbdatabase/createobjectstore/index.md index 0e051f61c00a76..0a0962439da729 100644 --- a/files/zh-cn/web/api/idbdatabase/createobjectstore/index.md +++ b/files/zh-cn/web/api/idbdatabase/createobjectstore/index.md @@ -44,47 +44,47 @@ var objectStore = IDBDatabase.createObjectStore(name, options); This method may raise a 此方法可能会抛出一个 {{domxref("DOMException")}} 带有以下所列其中一种类型的 {{domxref("DOMError")}} : -| Exception | Description | -| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `InvalidStateError` | 在非`versionchange`事务中调用时发生。在一些旧版本的 Webkit 浏览器,你必须先调用{{APIRef("IDBVersionChangeRequest.setVersion")}}方法。 | +| Exception | Description | +| -------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `InvalidStateError` | 在非`versionchange`事务中调用时发生。在一些旧版本的 Webkit 浏览器,你必须先调用{{APIRef("IDBVersionChangeRequest.setVersion")}}方法。 | | `TransactionInactiveError` | 如果对不存在的源数据库发出请求(例如,已被删除的)。此外,在 Firefox 版本小于 41 中,会抛出误导性的 `InvalidStateError` 错误,这一问题现已修复(请参阅 [Firefox bug 1176165](https://bugzil.la/1176165))。 | -| `ConstraintError` | 数据库中已存同名的对象存储(名字区分大小写) | -| `InvalidAccessError` | 如果 `autoIncrement` 设置为 true,并且 keyPath 是空字符串或包含空字符串的数组。 | +| `ConstraintError` | 数据库中已存同名的对象存储(名字区分大小写) | +| `InvalidAccessError` | 如果 `autoIncrement` 设置为 true,并且 keyPath 是空字符串或包含空字符串的数组。 | ## Example ```js - // 打开一个数据库 - var request = window.indexedDB.open("toDoList", 4); - - // This handler is called when a new version of the database - // is created, either when one has not been created before - // or when a new version number is submitted by calling - // window.indexedDB.open(). - // This handler is only supported in recent browsers. - request.onupgradeneeded = function(event) { - var db = event.target.result; - - db.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; - }; +// 打开一个数据库 +var request = window.indexedDB.open("toDoList", 4); + +// This handler is called when a new version of the database +// is created, either when one has not been created before +// or when a new version number is submitted by calling +// window.indexedDB.open(). +// This handler is only supported in recent browsers. +request.onupgradeneeded = function (event) { + var db = event.target.result; + + db.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; + }; - // Create an objectStore for this database + // Create an objectStore for this database - var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); - // define what data items the objectStore will contain + // define what data items the objectStore will contain - objectStore.createIndex("hours", "hours", { unique: false }); - objectStore.createIndex("minutes", "minutes", { unique: false }); - objectStore.createIndex("day", "day", { unique: false }); - objectStore.createIndex("month", "month", { unique: false }); - objectStore.createIndex("year", "year", { unique: false }); + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); - objectStore.createIndex("notified", "notified", { unique: false }); + objectStore.createIndex("notified", "notified", { unique: false }); - note.innerHTML += '
  • Object store created.
  • '; - }; + note.innerHTML += "
  • Object store created.
  • "; +}; ``` ## Specification diff --git a/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.md b/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.md index 84ca0ed06eaecc..68cc165bb6da60 100644 --- a/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.md +++ b/files/zh-cn/web/api/idbdatabase/deleteobjectstore/index.md @@ -26,11 +26,11 @@ dbInstance.deleteObjectStore(name); 此方法可能会引发下列 {{domxref("DOMException")}} 异常: -| Exception | Description | -| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `InvalidStateError` | Occurs if the method was not called from a `versionchange` transaction callback. For older WebKit browsers, you must call {{ APIRef("IDBVersionChangeRequest.setVersion")}} first. | +| Exception | Description | +| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `InvalidStateError` | Occurs if the method was not called from a `versionchange` transaction callback. For older WebKit browsers, you must call {{ APIRef("IDBVersionChangeRequest.setVersion")}} first. | | `TransactionInactiveError` | Occurs if a request is made on a source database that doesn't exist (e.g. has been deleted or removed.) In Firefox previous to version 41, an `InvalidStateError` was raised in this case as well, which was misleading; this has now been fixed (see [Firefox bug 1176165](https://bugzil.la/1176165).) | -| `NotFoundError` | You are trying to delete an object store that does not exist. Names are case sensitive. | +| `NotFoundError` | You are trying to delete an object store that does not exist. Names are case sensitive. | ## 示例 @@ -39,7 +39,7 @@ var dbName = "sampleDB"; var dbVersion = 2; var request = indexedDB.open(dbName, dbVersion); -request.onupgradeneeded = function(e) { +request.onupgradeneeded = function (e) { var db = request.result; if (e.oldVersion < 1) { db.createObjectStore("store1"); diff --git a/files/zh-cn/web/api/idbdatabase/index.md b/files/zh-cn/web/api/idbdatabase/index.md index c8f0edc35ec1db..081fa6a73c954f 100644 --- a/files/zh-cn/web/api/idbdatabase/index.md +++ b/files/zh-cn/web/api/idbdatabase/index.md @@ -53,54 +53,54 @@ IndexedDB 中的 **`IDBDatabase`** 接口提供一个到 [数据库的连接](/z ```js // 我们先打开一个数据库 - var DBOpenRequest = window.indexedDB.open("toDoList", 4); +var DBOpenRequest = window.indexedDB.open("toDoList", 4); - // 当数据库打开出错/成功时,以下两个事件处理程序将分别对 IDBDatabase 对象进行下一步操作 - DBOpenRequest.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; - }; +// 当数据库打开出错/成功时,以下两个事件处理程序将分别对 IDBDatabase 对象进行下一步操作 +DBOpenRequest.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; +}; - DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; - // 将打开数据库的结果存储在 db 变量中,该变量将在后面的代码中被频繁使用 - db = DBOpenRequest.result; + // 将打开数据库的结果存储在 db 变量中,该变量将在后面的代码中被频繁使用 + db = DBOpenRequest.result; - // 运行 displayData() 方法,用 IDB 中已经存在的所有待办事项列表数据填充到任务列表中 - displayData(); - }; + // 运行 displayData() 方法,用 IDB 中已经存在的所有待办事项列表数据填充到任务列表中 + displayData(); +}; - // 当试图打开一个尚未被创建的数据库,或者试图连接一个数据库还没被创立的版本时,onupgradeneeded 事件会被触发 +// 当试图打开一个尚未被创建的数据库,或者试图连接一个数据库还没被创立的版本时,onupgradeneeded 事件会被触发 - DBOpenRequest.onupgradeneeded = function(event) { - var db = event.target.result; +DBOpenRequest.onupgradeneeded = function (event) { + var db = event.target.result; - db.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; - }; + db.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; + }; - // 使用 IDBDatabase.createObjectStore 方法,可创建一个对象存储区 + // 使用 IDBDatabase.createObjectStore 方法,可创建一个对象存储区 - var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); - // 定义 objectStore 将包含哪些数据项 + // 定义 objectStore 将包含哪些数据项 - objectStore.createIndex("hours", "hours", { unique: false }); - objectStore.createIndex("minutes", "minutes", { unique: false }); - objectStore.createIndex("day", "day", { unique: false }); - objectStore.createIndex("month", "month", { unique: false }); - objectStore.createIndex("year", "year", { unique: false }); + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); - objectStore.createIndex("notified", "notified", { unique: false }); + objectStore.createIndex("notified", "notified", { unique: false }); - note.innerHTML += '
  • Object store created.
  • '; - }; + note.innerHTML += "
  • Object store created.
  • "; +}; ``` 下一行打开数据库上的事务,然后打开一个对象存储,然后我们可以在其中操作数据。 ```js - var objectStore = db.transaction('toDoList').objectStore('toDoList'); +var objectStore = db.transaction("toDoList").objectStore("toDoList"); ``` ## 规范 diff --git a/files/zh-cn/web/api/idbfactory/index.md b/files/zh-cn/web/api/idbfactory/index.md index c7d4817ccc3c78..67dbdf711b5dae 100644 --- a/files/zh-cn/web/api/idbfactory/index.md +++ b/files/zh-cn/web/api/idbfactory/index.md @@ -29,23 +29,31 @@ In the following code snippet, we make a request to open a database, and include var note = document.querySelector("ul"); // In the following line, you should include the prefixes of implementations you want to test. -window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; +window.indexedDB = + window.indexedDB || + window.mozIndexedDB || + window.webkitIndexedDB || + window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB* objects: -window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; -window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; +window.IDBTransaction = + window.IDBTransaction || + window.webkitIDBTransaction || + window.msIDBTransaction; +window.IDBKeyRange = + window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*) // Let us open version 4 of our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); // these two event handlers act on the database being opened successfully, or not -DBOpenRequest.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; +DBOpenRequest.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; }; -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. This is used a lot later on, for opening transactions and suchlike. db = request.result; diff --git a/files/zh-cn/web/api/idbfactory/open/index.md b/files/zh-cn/web/api/idbfactory/open/index.md index 8914d43543d55b..cd6c160f67482a 100644 --- a/files/zh-cn/web/api/idbfactory/open/index.md +++ b/files/zh-cn/web/api/idbfactory/open/index.md @@ -11,8 +11,8 @@ slug: Web/API/IDBFactory/open 1. 指定数据库已经存在时: - - 等待 {{domxref("versionchange")}} 操作完成。 - - 如果数据库已计划删除,那等着删除完成。 + - 等待 {{domxref("versionchange")}} 操作完成。 + - 如果数据库已计划删除,那等着删除完成。 2. 如果已有数据库版本高于给定的 `version`,中止操作并返回类型为 `VersionError` 的 `DOMError`。 3. 如果已有数据库版本低于给定的 `version`,触发一个 `versionchange` 操作。 @@ -48,7 +48,10 @@ var request = window.indexedDB.open("toDoList", 4); For the experimental version with `options` (see below): ```js -var request = window.indexedDB.open("toDoList", {version: 4, storage: "temporary"}); +var request = window.indexedDB.open("toDoList", { + version: 4, + storage: "temporary", +}); ``` ## 参数 diff --git a/files/zh-cn/web/api/idbkeyrange/index.md b/files/zh-cn/web/api/idbkeyrange/index.md index b73a56b1c36885..7e937f4fac9c04 100644 --- a/files/zh-cn/web/api/idbkeyrange/index.md +++ b/files/zh-cn/web/api/idbkeyrange/index.md @@ -9,17 +9,17 @@ slug: Web/API/IDBKeyRange 键范围可以是单个值,也可以是具有上界、下界或端点的范围。如果键范围同时有上界或下界,那么它是有界的,否则是无界的。有界键范围可以是开放的(不包含端点)或闭合的(包含了端点)。要检索一定范围内的所有键值,可以使用以下的代码结构: -| Range | Code | -| --------------------------- | ----------------------------------------------------------------- | -| All keys ≤ **x** | {{domxref("IDBKeyRange.upperBound")}}`(x)` | -| All keys < **x** | {{domxref("IDBKeyRange.upperBound")}}`(x, true)` | -| All keys ≥ **y** | {{domxref("IDBKeyRange.lowerBound")}}`(y)` | -| All keys > **y** | {{domxref("IDBKeyRange.lowerBound")}}`(y, true)` | +| Range | Code | +| --------------------------- | ----------------------------------------------------- | +| All keys ≤ **x** | {{domxref("IDBKeyRange.upperBound")}}`(x)` | +| All keys < **x** | {{domxref("IDBKeyRange.upperBound")}}`(x, true)` | +| All keys ≥ **y** | {{domxref("IDBKeyRange.lowerBound")}}`(y)` | +| All keys > **y** | {{domxref("IDBKeyRange.lowerBound")}}`(y, true)` | | All keys ≥ **x** && ≤ **y** | {{domxref("IDBKeyRange.bound")}}`(x, y)` | | All keys > **x** &&< **y** | {{domxref("IDBKeyRange.bound")}}`(x, y, true, true)` | | All keys > **x** && ≤ **y** | {{domxref("IDBKeyRange.bound")}}`(x, y, true, false)` | | All keys ≥ **x** &&< **y** | {{domxref("IDBKeyRange.bound")}}`(x, y, false, true)` | -| The key = **z** | {{domxref("IDBKeyRange.only")}}`(z)` | +| The key = **z** | {{domxref("IDBKeyRange.only")}}`(z)` | 如果以下条件为 true,则键包含在键范围中: @@ -76,19 +76,20 @@ slug: Web/API/IDBKeyRange function displayData() { var keyRangeValue = IDBKeyRange.bound("A", "F"); - var transaction = db.transaction(['fThings'], 'readonly'); - var objectStore = transaction.objectStore('fThings'); + var transaction = db.transaction(["fThings"], "readonly"); + var objectStore = transaction.objectStore("fThings"); - objectStore.openCursor(keyRangeValue).onsuccess = function(event) { + objectStore.openCursor(keyRangeValue).onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { - var listItem = document.createElement('li'); - listItem.innerHTML = '' + cursor.value.fThing + ', ' + cursor.value.fRating; + if (cursor) { + var listItem = document.createElement("li"); + listItem.innerHTML = + "" + cursor.value.fThing + ", " + cursor.value.fRating; list.appendChild(listItem); cursor.continue(); } else { - console.log('Entries all displayed.'); + console.log("Entries all displayed."); } }; } diff --git a/files/zh-cn/web/api/idbkeyrange/lowerbound_static/index.md b/files/zh-cn/web/api/idbkeyrange/lowerbound_static/index.md index 0873a3afb34ebf..6cc90bcb010133 100644 --- a/files/zh-cn/web/api/idbkeyrange/lowerbound_static/index.md +++ b/files/zh-cn/web/api/idbkeyrange/lowerbound_static/index.md @@ -46,22 +46,23 @@ var myIDBKeyRange = IDBKeyRange.lowerBound(lower, open); function displayData() { var keyRangeValue = IDBKeyRange.lowerBound("F"); - var transaction = db.transaction(['fThings'], 'readonly'); - var objectStore = transaction.objectStore('fThings'); + var transaction = db.transaction(["fThings"], "readonly"); + var objectStore = transaction.objectStore("fThings"); - objectStore.openCursor(keyRangeValue).onsuccess = function(event) { + objectStore.openCursor(keyRangeValue).onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { - var listItem = document.createElement('li'); - listItem.innerHTML = '' + cursor.value.fThing + ', ' + cursor.value.fRating; - list.appendChild(listItem); - - cursor.continue(); - } else { - console.log('Entries all displayed.'); - } - }; + if (cursor) { + var listItem = document.createElement("li"); + listItem.innerHTML = + "" + cursor.value.fThing + ", " + cursor.value.fRating; + list.appendChild(listItem); + + cursor.continue(); + } else { + console.log("Entries all displayed."); + } }; +} ``` ## Specification diff --git a/files/zh-cn/web/api/idbobjectstore/add/index.md b/files/zh-cn/web/api/idbobjectstore/add/index.md index ab64307b09b104..08d0dccf59af96 100644 --- a/files/zh-cn/web/api/idbobjectstore/add/index.md +++ b/files/zh-cn/web/api/idbobjectstore/add/index.md @@ -98,8 +98,8 @@ var request = objectStore.add(value, key); // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -111,18 +111,29 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready to insert into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -131,11 +142,11 @@ function addData() { // Make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our request - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; -}; +} ``` ## Specification diff --git a/files/zh-cn/web/api/idbobjectstore/autoincrement/index.md b/files/zh-cn/web/api/idbobjectstore/autoincrement/index.md index d0e76518c19cdd..d257300720c8e5 100644 --- a/files/zh-cn/web/api/idbobjectstore/autoincrement/index.md +++ b/files/zh-cn/web/api/idbobjectstore/autoincrement/index.md @@ -36,8 +36,8 @@ var myAutoIncrement = objectStore.autoIncrement; // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -49,18 +49,29 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready to insert into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -70,11 +81,11 @@ function addData() { // Make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our request - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; -}; +} ``` ## 规范 diff --git a/files/zh-cn/web/api/idbobjectstore/get/index.md b/files/zh-cn/web/api/idbobjectstore/get/index.md index dbd68d5d0c7377..812b57caf81a8c 100644 --- a/files/zh-cn/web/api/idbobjectstore/get/index.md +++ b/files/zh-cn/web/api/idbobjectstore/get/index.md @@ -32,10 +32,10 @@ var request = objectStore.get(key); 此方法可能会引发以下类型之一的 {{domxref("DOMException")}} : -| Exception | Description | -| ------------------------ | ------------------------------------------------------------------------- | +| Exception | Description | +| ------------------------ | -------------------------------------------------------------- | | TransactionInactiveError | This {{domxref("IDBObjectStore")}}'s transaction is inactive. | -| DataError | The key or key range provided contains an invalid key. | +| DataError | The key or key range provided contains an invalid key. | | `InvalidStateError` | The {{domxref("IDBObjectStore")}} has been deleted or removed. | ## 例子 @@ -46,8 +46,8 @@ var request = objectStore.get(key); // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -62,12 +62,13 @@ function getData() { var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error: ' + transaction.error + '
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error: " + transaction.error + "
  • "; }; // create an object store on the transaction @@ -76,14 +77,13 @@ function getData() { // Make a request to get a record by key from the object store var objectStoreRequest = objectStore.get("Walk dog"); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our request - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; var myRecord = objectStoreRequest.result; }; - -}; +} ``` ## 规范 diff --git a/files/zh-cn/web/api/idbobjectstore/index.md b/files/zh-cn/web/api/idbobjectstore/index.md index 924788a9f7e6af..b7f9d15e30e0d9 100644 --- a/files/zh-cn/web/api/idbobjectstore/index.md +++ b/files/zh-cn/web/api/idbobjectstore/index.md @@ -13,27 +13,27 @@ slug: Web/API/IDBObjectStore ## 方法预览 -| `IDBRequest add (in any value, in optional any key) raises (DOMException);` | -| -------------------------------------------------------------------------------------------------------------------------------------------- | -| `IDBRequest clear() raises (DOMException);` | -| `IDBRequest count (in optional any key) raises (DOMException);` | +| `IDBRequest add (in any value, in optional any key) raises (DOMException);` | +| ------------------------------------------------------------------------------------------------------------------- | +| `IDBRequest clear() raises (DOMException);` | +| `IDBRequest count (in optional any key) raises (DOMException);` | | `IDBIndex createIndex (in DOMString name, in DOMString keyPath, in optional boolean unique) raises (DOMException);` | -| ` IDBRequest delete (in any key) raises (DOMException); ` | -| `void deleteIndex (in any DOMString indexName) raises (DOMException); | -| `IDBRequest get (in any key) raises (DOMException);` | +| `IDBRequest delete (in any key) raises (DOMException);` | +| `void deleteIndex (in any DOMString indexName) raises (DOMException); | +| `IDBRequest get (in any key) raises (DOMException);` | | `IDBIndex index (in DOMString name) raises (DOMException);` | -| `IDBRequest openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises(DOMException);` | -| `IDBRequest put (in any value, in optional any key) raises (DOMException);` | +| `IDBRequest openCursor (in optional IDBKeyRange range, in optional unsigned short direction) raises(DOMException);` | +| `IDBRequest put (in any value, in optional any key) raises (DOMException);` | ## 属性 -| Attribute | Type | Description | -| --------------- | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------- | +| Attribute | Type | Description | +| --------------- | ------------------------------------------- | -------------------------------------------------------------------------------------------------- | | `indexNames` | `readonly DOMStringList` | 表中对象的[索引](/zh-CN/IndexedDB#gloss_index)名列表。 | | `keyPath` | `readonly` [`DOMString`](/En/DOM/DOMString) | 表中的[键路径](/zh-CN/IndexedDB#gloss_key_path),如果该属性为 null,每次操作表时必须提供一个键名。 | -| `name` | `readonly` [`DOMString`](/En/DOM/DOMString) | 表名 | -| `transaction` | `readonly IDBTransaction` | 事务的名称,该表属于此事务。 | -| `autoIncrement` | `readonly boolean` | 表中自增字段的值 | +| `name` | `readonly` [`DOMString`](/En/DOM/DOMString) | 表名 | +| `transaction` | `readonly IDBTransaction` | 事务的名称,该表属于此事务。 | +| `autoIncrement` | `readonly boolean` | 表中自增字段的值 | ## 方法 @@ -239,7 +239,7 @@ This method may raise a [DOMException](/zh-CN/docs/DOM/DOMException) with a [DOM > **备注:** If the key that identifies the record is a Number, the key passed to the delete method must be a Number too, and not a String. So for example you might need to do the following: > > ```js -> var key_val = '42'; +> var key_val = "42"; > var key = Number(key_val); > objectstore.delete(key); > ``` @@ -446,8 +446,8 @@ This example shows a variety of different uses of object stores, from updating t // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in db. db = DBOpenRequest.result; @@ -457,11 +457,11 @@ DBOpenRequest.onsuccess = function(event) { // the database needs to be created Either one has not // been created before, or a new version number has been // submitted via the window.indexedDB.open line above -DBOpenRequest.onupgradeneeded = function(event) { +DBOpenRequest.onupgradeneeded = function (event) { var db = event.target.result; - db.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; + db.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; }; // Create an objectStore for this database @@ -478,24 +478,33 @@ DBOpenRequest.onupgradeneeded = function(event) { objectStore.createIndex("notified", "notified", { unique: false }); - note.innerHTML += '
  • Object store created.
  • '; + note.innerHTML += "
  • Object store created.
  • "; }; // Create a new item to add in to the object store var newItem = [ - { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: 'December', year: 2013, notified: "no" } + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done -transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; +transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; -transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; +transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -503,9 +512,9 @@ var objectStore = transaction.objectStore("toDoList"); // make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); -objectStoreRequest.onsuccess = function(event) { - note.innerHTML += '
  • Request successful .
  • '; -} +objectStoreRequest.onsuccess = function (event) { + note.innerHTML += "
  • Request successful .
  • "; +}; ``` ## Specifications diff --git a/files/zh-cn/web/api/idbobjectstore/indexnames/index.md b/files/zh-cn/web/api/idbobjectstore/indexnames/index.md index 482ab3e74e7f3a..a6b98bb9b70e04 100644 --- a/files/zh-cn/web/api/idbobjectstore/indexnames/index.md +++ b/files/zh-cn/web/api/idbobjectstore/indexnames/index.md @@ -27,8 +27,8 @@ var myindexNames = objectStore.indexNames; // 让我们来打开我们的数据库 var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // 将打开数据库的结果存储在 db 变量中 // 下面经常用到这个 @@ -40,19 +40,29 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // 创建一个新对象以准备插入到 IDB 中 - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // 打开读/写数据库事务,准备添加数据 var transaction = db.transaction(["toDoList"], "readwrite"); // 当所有事情都完成时,报告事务完成的成功情况 - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // 在事务上创建对象存储 @@ -62,11 +72,11 @@ function addData() { // 请求将 newItem 对象 添加到对象存储区 var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // 报告我们请求的成功 - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; -}; +} ``` ## 规范 diff --git a/files/zh-cn/web/api/idbobjectstore/keypath/index.md b/files/zh-cn/web/api/idbobjectstore/keypath/index.md index 0f9eab311a7780..b19579d9ceaa01 100644 --- a/files/zh-cn/web/api/idbobjectstore/keypath/index.md +++ b/files/zh-cn/web/api/idbobjectstore/keypath/index.md @@ -33,8 +33,8 @@ var mykeyPath = objectStore.keyPath; // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -46,18 +46,29 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready to insert into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of the transaction completing, when everything is done - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += "
  • Transaction completed.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -67,11 +78,11 @@ function addData() { // Make a request to add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our request - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; -}; +} ``` ## 规范 diff --git a/files/zh-cn/web/api/idbobjectstore/opencursor/index.md b/files/zh-cn/web/api/idbobjectstore/opencursor/index.md index f3b61f521907a9..3bf93542c8ba47 100644 --- a/files/zh-cn/web/api/idbobjectstore/opencursor/index.md +++ b/files/zh-cn/web/api/idbobjectstore/opencursor/index.md @@ -32,11 +32,11 @@ var request = ObjectStore.openCursor(query, direction); 此方法可能引起以下类型之一的 {{domxref("DOMException")}} : -| 异常 | 描述 | -| -------------------------- | ----------------------------------------------------------------------------------------- | +| 异常 | 描述 | +| -------------------------- | --------------------------------------------------------------------- | | `InvalidStateError` | 此 {{domxref("IDBObjectStore")}} 或{{domxref("IDBIndex")}} 已被删除。 | -| `TransactionInactiveError` | 此 {{domxref("IDBObjectStore")}} 的事务处于非活动状态。 | -| `DataError` | 指定的键或键范围无效。 | +| `TransactionInactiveError` | 此 {{domxref("IDBObjectStore")}} 的事务处于非活动状态。 | +| `DataError` | 指定的键或键范围无效。 | ## 例子 @@ -46,9 +46,9 @@ var request = ObjectStore.openCursor(query, direction); var transaction = db.transaction("name", "readonly"); var objectStore = transaction.objectStore("name"); var request = objectStore.openCursor(); -request.onsuccess = function(event) { +request.onsuccess = function (event) { var cursor = event.target.result; - if(cursor) { + if (cursor) { // cursor.value 包含正在被遍历的当前记录 // 这里你可以对 result 做些什么 cursor.continue(); diff --git a/files/zh-cn/web/api/idbobjectstore/put/index.md b/files/zh-cn/web/api/idbobjectstore/put/index.md index 92fc720f8bd3a3..65038b3037bcad 100644 --- a/files/zh-cn/web/api/idbobjectstore/put/index.md +++ b/files/zh-cn/web/api/idbobjectstore/put/index.md @@ -113,12 +113,14 @@ The following example requests a given record title; when that request is succes var title = "Walk dog"; // Open up a transaction as usual -var objectStore = db.transaction(['toDoList'], "readwrite").objectStore('toDoList'); +var objectStore = db + .transaction(["toDoList"], "readwrite") + .objectStore("toDoList"); // Get the to-do list object that has this title as it's title var objectStoreTitleRequest = objectStore.get(title); -objectStoreTitleRequest.onsuccess = function() { +objectStoreTitleRequest.onsuccess = function () { // Grab the data object returned as the result var data = objectStoreTitleRequest.result; @@ -129,10 +131,13 @@ objectStoreTitleRequest.onsuccess = function() { var updateTitleRequest = objectStore.put(data); // Log the transaction that originated this request - console.log("The transaction that originated this request is " + updateTitleRequest.transaction); + console.log( + "The transaction that originated this request is " + + updateTitleRequest.transaction, + ); // When this new request succeeds, run the displayData() function again to update the display - updateTitleRequest.onsuccess = function() { + updateTitleRequest.onsuccess = function () { displayData(); }; }; diff --git a/files/zh-cn/web/api/idbopendbrequest/index.md b/files/zh-cn/web/api/idbopendbrequest/index.md index 4b09645602388b..af10b33997fc56 100644 --- a/files/zh-cn/web/api/idbopendbrequest/index.md +++ b/files/zh-cn/web/api/idbopendbrequest/index.md @@ -37,12 +37,12 @@ var db; var DBOpenRequest = window.indexedDB.open("toDoList", 4); // these event handlers act on the database being opened. -DBOpenRequest.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; +DBOpenRequest.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; }; -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db // variable. This is used a lot below @@ -58,11 +58,11 @@ DBOpenRequest.onsuccess = function(event) { // been created before, or a new version number has been // submitted via the window.indexedDB.open line above // it is only implemented in recent browsers -DBOpenRequest.onupgradeneeded = function(event) { +DBOpenRequest.onupgradeneeded = function (event) { var db = this.result; - db.onerror = function(event) { - note.innerHTML += '
  • Error loading database.
  • '; + db.onerror = function (event) { + note.innerHTML += "
  • Error loading database.
  • "; }; // Create an objectStore for this database diff --git a/files/zh-cn/web/api/idbtransaction/complete_event/index.md b/files/zh-cn/web/api/idbtransaction/complete_event/index.md index 865b1d1152e04d..f47075a62ed3b3 100644 --- a/files/zh-cn/web/api/idbtransaction/complete_event/index.md +++ b/files/zh-cn/web/api/idbtransaction/complete_event/index.md @@ -1,5 +1,5 @@ --- -title: 'IDBTransaction: complete event' +title: "IDBTransaction: complete event" slug: Web/API/IDBTransaction/complete_event --- @@ -36,39 +36,46 @@ Using {{DOMxRef("EventTarget.addEventListener", "addEventListener()")}}: ```js // Open the database -const DBOpenRequest = window.indexedDB.open('toDoList', 4); +const DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onupgradeneeded = event => { +DBOpenRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { - console.log('Error creating database'); + console.log("Error creating database"); }; // Create an objectStore for this database - var objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' }); + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); // define what data items the objectStore will contain - objectStore.createIndex('hours', 'hours', { unique: false }); - objectStore.createIndex('minutes', 'minutes', { unique: false }); - objectStore.createIndex('day', 'day', { unique: false }); - objectStore.createIndex('month', 'month', { unique: false }); - objectStore.createIndex('year', 'year', { unique: false }); + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); }; -DBOpenRequest.onsuccess = event => { +DBOpenRequest.onsuccess = (event) => { const db = DBOpenRequest.result; // open a read/write db transaction, ready for adding the data - const transaction = db.transaction(['toDoList'], 'readwrite'); + const transaction = db.transaction(["toDoList"], "readwrite"); // add a listener for `complete` - transaction.addEventListener('complete', event => { - console.log('Transaction was competed'); + transaction.addEventListener("complete", (event) => { + console.log("Transaction was competed"); }); - const objectStore = transaction.objectStore('toDoList'); - const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 }; + const objectStore = transaction.objectStore("toDoList"); + const newItem = { + taskTitle: "my task", + hours: 10, + minutes: 10, + day: 10, + month: "January", + year: 2019, + }; const objectStoreRequest = objectStore.add(newItem); }; ``` @@ -77,39 +84,46 @@ Using the {{DOMxRef("IDBTransaction.oncomplete", "oncomplete")}} property: ```js // Open the database -const DBOpenRequest = window.indexedDB.open('toDoList', 4); +const DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onupgradeneeded = event => { +DBOpenRequest.onupgradeneeded = (event) => { const db = event.target.result; db.onerror = () => { - console.log('Error creating database'); + console.log("Error creating database"); }; // Create an objectStore for this database - var objectStore = db.createObjectStore('toDoList', { keyPath: 'taskTitle' }); + var objectStore = db.createObjectStore("toDoList", { keyPath: "taskTitle" }); // define what data items the objectStore will contain - objectStore.createIndex('hours', 'hours', { unique: false }); - objectStore.createIndex('minutes', 'minutes', { unique: false }); - objectStore.createIndex('day', 'day', { unique: false }); - objectStore.createIndex('month', 'month', { unique: false }); - objectStore.createIndex('year', 'year', { unique: false }); + objectStore.createIndex("hours", "hours", { unique: false }); + objectStore.createIndex("minutes", "minutes", { unique: false }); + objectStore.createIndex("day", "day", { unique: false }); + objectStore.createIndex("month", "month", { unique: false }); + objectStore.createIndex("year", "year", { unique: false }); }; -DBOpenRequest.onsuccess = event => { +DBOpenRequest.onsuccess = (event) => { const db = DBOpenRequest.result; // open a read/write db transaction, ready for adding the data - const transaction = db.transaction(['toDoList'], 'readwrite'); + const transaction = db.transaction(["toDoList"], "readwrite"); // add a listener for `complete` - transaction.oncomplete = event => { - console.log('Transaction was competed'); + transaction.oncomplete = (event) => { + console.log("Transaction was competed"); }; - const objectStore = transaction.objectStore('toDoList'); - const newItem = { taskTitle: 'my task', hours: 10, minutes: 10, day: 10, month: 'January', year: 2019 }; + const objectStore = transaction.objectStore("toDoList"); + const newItem = { + taskTitle: "my task", + hours: 10, + minutes: 10, + day: 10, + month: "January", + year: 2019, + }; const objectStoreRequest = objectStore.add(newItem); }; ``` diff --git a/files/zh-cn/web/api/idbtransaction/db/index.md b/files/zh-cn/web/api/idbtransaction/db/index.md index 8d495cd727bd14..4d186bb6e78b6d 100644 --- a/files/zh-cn/web/api/idbtransaction/db/index.md +++ b/files/zh-cn/web/api/idbtransaction/db/index.md @@ -27,8 +27,8 @@ In the following code snippet, we open a read/write transaction on our database // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. // This is used a lot below @@ -40,18 +40,30 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready for being inserted into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of opening the transaction - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed: database modification finished.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += + "
  • Transaction completed: database modification finished.
  • "; }; - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -60,15 +72,15 @@ function addData() { // add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of the request (this does not mean the item // has been stored successfully in the DB - for that you need transaction.onsuccess) - note.innerHTML += '
  • Request successful.
  • '; + note.innerHTML += "
  • Request successful.
  • "; }; // Return the database (IDBDatabase) connection with which this transaction is associated transaction.db; -}; +} ``` ## Specification diff --git a/files/zh-cn/web/api/idbtransaction/index.md b/files/zh-cn/web/api/idbtransaction/index.md index 80950f2ed4c18c..829d42e522e7dc 100644 --- a/files/zh-cn/web/api/idbtransaction/index.md +++ b/files/zh-cn/web/api/idbtransaction/index.md @@ -16,8 +16,8 @@ If you must ensure durability for some reason (e.g. you're storing critical data ```js var trans1 = db.transaction("foo", "readwrite"); var trans2 = db.transaction("foo", "readwrite"); -var objectStore2 = trans2.objectStore("foo") -var objectStore1 = trans1.objectStore("foo") +var objectStore2 = trans2.objectStore("foo"); +var objectStore1 = trans1.objectStore("foo"); objectStore2.put("2", "key"); objectStore1.put("1", "key"); ``` @@ -82,16 +82,17 @@ Transactions can fail for a fixed number of reasons, all of which (except the us Transactions 可使用以下三种模式中的一种: -| 常量 | 值 | 描述 | -| -------------------- | ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `READ_ONLY` | "readonly"(0 in Chrome) | 允许读取数据,不改变。 | -| `READ_WRITE` | "readwrite"(1 in Chrome) | 允许读取和写入现有数据存储,数据被改变。 | +| 常量 | 值 | 描述 | +| ---------------- | ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `READ_ONLY` | "readonly"(0 in Chrome) | 允许读取数据,不改变。 | +| `READ_WRITE` | "readwrite"(1 in Chrome) | 允许读取和写入现有数据存储,数据被改变。 | | `VERSION_CHANGE` | "versionchange"(2 in Chrome) | 允许执行任何操作,包括删除和创建对象存储和索引。此模式是用于开始使用[IDBDatabase](/zh-CN/docs/IndexedDB/IDBDatabase) 的 [`setVersion()`](/zh-CN/docs/IndexedDB/IDBDatabase#setVersion)方法更新版本号事务。这种模式的事务无法与其他事务并发运行。这种模式下的事务被称为“升级事务”。 | 即使目前这些常量已经被废弃,但如果你需要使用它,则需要提供向下兼容方案 (in Chrome [the change was made in version 21](http://peter.sh/2012/05/tab-sizing-string-values-for-indexeddb-and-chrome-21/))。你应当防止出现对象不存在的情况: ```js -var myIDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || { READ_WRITE: "readwrite" }; +var myIDBTransaction = window.IDBTransaction || + window.webkitIDBTransaction || { READ_WRITE: "readwrite" }; ``` ## Example @@ -102,8 +103,8 @@ In the following code snippet, we open a read/write transaction on our database // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); -DBOpenRequest.onsuccess = function(event) { - note.innerHTML += '
  • Database initialised.
  • '; +DBOpenRequest.onsuccess = function (event) { + note.innerHTML += "
  • Database initialised.
  • "; // store the result of opening the database in the db variable. This is used a lot below db = DBOpenRequest.result; @@ -114,19 +115,30 @@ DBOpenRequest.onsuccess = function(event) { function addData() { // Create a new object ready for being inserted into the IDB - var newItem = [ { taskTitle: "Walk dog", hours: 19, minutes: 30, day: 24, month: "December", year: 2013, notified: "no" } ]; + var newItem = [ + { + taskTitle: "Walk dog", + hours: 19, + minutes: 30, + day: 24, + month: "December", + year: 2013, + notified: "no", + }, + ]; // open a read/write db transaction, ready for adding the data var transaction = db.transaction(["toDoList"], "readwrite"); // report on the success of opening the transaction - transaction.oncomplete = function(event) { - note.innerHTML += '
  • Transaction completed: database modification finished.
  • '; + transaction.oncomplete = function (event) { + note.innerHTML += + "
  • Transaction completed: database modification finished.
  • "; }; - - transaction.onerror = function(event) { - note.innerHTML += '
  • Transaction not opened due to error. Duplicate items not allowed.
  • '; + transaction.onerror = function (event) { + note.innerHTML += + "
  • Transaction not opened due to error. Duplicate items not allowed.
  • "; }; // create an object store on the transaction @@ -135,11 +147,11 @@ function addData() { // add our newItem object to the object store var objectStoreRequest = objectStore.add(newItem[0]); - objectStoreRequest.onsuccess = function(event) { + objectStoreRequest.onsuccess = function (event) { // report the success of our new item going into the database - note.innerHTML += '
  • New item added to database.
  • '; + note.innerHTML += "
  • New item added to database.
  • "; }; -}; +} ``` ## Specifications diff --git a/files/zh-cn/web/api/imagedata/width/index.md b/files/zh-cn/web/api/imagedata/width/index.md index dc1d3d9b9d1285..a23175f75ab73f 100644 --- a/files/zh-cn/web/api/imagedata/width/index.md +++ b/files/zh-cn/web/api/imagedata/width/index.md @@ -17,7 +17,7 @@ imagedata.width ```js var imagedata = new ImageData(100, 100); -imagedata.width // 100 +imagedata.width; // 100 ``` ## 规范 diff --git a/files/zh-cn/web/api/indexeddb/index.md b/files/zh-cn/web/api/indexeddb/index.md index 4df48e8e41e908..d103b9fcaf46fa 100644 --- a/files/zh-cn/web/api/indexeddb/index.md +++ b/files/zh-cn/web/api/indexeddb/index.md @@ -22,10 +22,10 @@ var IDBFactory = self.indexedDB; ```js var db; function openDB() { - var DBOpenRequest = window.indexedDB.open('toDoList'); - DBOpenRequest.onsuccess = function(e) { - db = DBOpenRequest.result; - } + var DBOpenRequest = window.indexedDB.open("toDoList"); + DBOpenRequest.onsuccess = function (e) { + db = DBOpenRequest.result; + }; } ``` diff --git a/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.md b/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.md index 1d48fd77447c52..9890936d2ecf9b 100644 --- a/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.md +++ b/files/zh-cn/web/api/indexeddb_api/checking_when_a_deadline_is_due/index.md @@ -115,11 +115,11 @@ function checkDeadlines() { First we grab the current date and time by creating a blank `Date` object. Easy huh? It's about to get a bit more complex. ```js - var minuteCheck = now.getMinutes(); - var hourCheck = now.getHours(); - var dayCheck = now.getDate(); - var monthCheck = now.getMonth(); - var yearCheck = now.getFullYear(); +var minuteCheck = now.getMinutes(); +var hourCheck = now.getHours(); +var dayCheck = now.getDate(); +var monthCheck = now.getMonth(); +var yearCheck = now.getFullYear(); ``` The `Date` object has a number of methods to extract various parts of the date and time inside it. Here we fetch the current minutes (gives an easy numerical value), hours (gives an easy numerical value), day of the month (`getDate()` is needed for this, as `getDay()` returns the day of the week, 1-7), month (returns a number from 0-11, see below), and year (`getFullYear()` is needed; `getYear()` is deprecated, and returns a weird value that is not much use to anyone!) @@ -136,38 +136,39 @@ The `Date` object has a number of methods to extract various parts of the date a Next we create another IndexedDB `objectStore`, and use the `openCursor()` method to open a cursor, which is basically a way in IndexedDB to iterate through all the items in the store. We then loop through all the items in the cursor for as long as there is a valid item left in the cursor. ```js - switch(cursor.value.month) { - case "January": - var monthNumber = 0; - break; - case "February": - var monthNumber = 1; - break; - - // other lines removed from listing for brevity - - case "December": - var monthNumber = 11; - break; - default: - alert('Incorrect month entered in database.'); - } +switch (cursor.value.month) { + case "January": + var monthNumber = 0; + break; + case "February": + var monthNumber = 1; + break; + + // other lines removed from listing for brevity + + case "December": + var monthNumber = 11; + break; + default: + alert("Incorrect month entered in database."); +} ``` 我们要做的第一件事是将我们存储在数据库中的月份名称转换为 JavaScript 将理解的月份号码。如前所述,JavaScript Date 对象将月份值创建为 0 到 11 之间的数字。 ```js - if(+(cursor.value.hours) == hourCheck && - +(cursor.value.minutes) == minuteCheck && - +(cursor.value.day) == dayCheck && - monthNumber == monthCheck && - cursor.value.year == yearCheck && - notified == "no") { - - // If the numbers all do match, run the createNotification() - // function to create a system notification - createNotification(cursor.value.taskTitle); - } +if ( + +cursor.value.hours == hourCheck && + +cursor.value.minutes == minuteCheck && + +cursor.value.day == dayCheck && + monthNumber == monthCheck && + cursor.value.year == yearCheck && + notified == "no" +) { + // If the numbers all do match, run the createNotification() + // function to create a system notification + createNotification(cursor.value.taskTitle); +} ``` With the current time and date segments that we want to check against the IndexedDB stored values all assembled, it is time to perform the checks. We want all the values to match before we show the user some kind of notification to tell them their deadline is up. diff --git a/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.md b/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.md index 943f44efef82e7..2390b78508aa8b 100644 --- a/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.md +++ b/files/zh-cn/web/api/indexeddb_api/using_indexeddb/index.md @@ -35,11 +35,19 @@ IndexedDB 鼓励使用的基本模式如下所示: ```js // In the following line, you should include the prefixes of implementations you want to test. -window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB; +window.indexedDB = + window.indexedDB || + window.mozIndexedDB || + window.webkitIndexedDB || + window.msIndexedDB; // DON'T use "var indexedDB = ..." if you're not in a function. // Moreover, you may need references to some window.IDB* objects: -window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction || window.msIDBTransaction; -window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange +window.IDBTransaction = + window.IDBTransaction || + window.webkitIDBTransaction || + window.msIDBTransaction; +window.IDBKeyRange = + window.IDBKeyRange || window.webkitIDBKeyRange || window.msIDBKeyRange; // (Mozilla has never prefixed these objects, so we don't need window.mozIDB*) ``` @@ -47,7 +55,9 @@ window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange || window.ms ```js if (!window.indexedDB) { - window.alert("Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.") + window.alert( + "Your browser doesn't support a stable version of IndexedDB. Such and such feature will not be available.", + ); } ``` @@ -77,10 +87,10 @@ open 请求不会立即打开数据库或者开始一个事务。对 `open()` 几乎所有我们产生的请求我们在处理的时候首先要做的就是添加成功和失败处理函数: ```js -request.onerror = function(event) { +request.onerror = function (event) { // Do something with request.errorCode! }; -request.onsuccess = function(event) { +request.onsuccess = function (event) { // Do something with request.result! }; ``` @@ -96,10 +106,10 @@ IndexedDB 的 API 被设计来尽可能地减少对错误处理的需求,所 ```js var db; var request = indexedDB.open("MyTestDatabase"); -request.onerror = function(event) { +request.onerror = function (event) { alert("Why didn't you allow my web app to use IndexedDB?!"); }; -request.onsuccess = function(event) { +request.onsuccess = function (event) { db = event.target.result; }; ``` @@ -109,7 +119,7 @@ request.onsuccess = function(event) { 如上文所述,错误事件遵循冒泡机制。错误事件都是针对产生这些错误的请求的,然后事件冒泡到事务,然后最终到达数据库对象。如果你希望避免为所有的请求都增加错误处理程序,你可以替代性的仅对数据库对象添加一个错误处理程序,像这样: ```js -db.onerror = function(event) { +db.onerror = function (event) { // Generic error handler for all errors targeted at this database's // requests! alert("Database error: " + event.target.errorCode); @@ -126,7 +136,7 @@ db.onerror = function(event) { ```js // 该事件仅在较新的浏览器中实现了 -request.onupgradeneeded = function(event) { +request.onupgradeneeded = function (event) { // 保存 IDBDataBase 接口 var db = event.target.result; @@ -166,7 +176,7 @@ WebKit/Blink 支持当前版本的规范,同时 Chrome 23+ 、Opera 17+ 以及 // 我们的客户数据看起来像这样。 const customerData = [ { ssn: "444-44-4444", name: "Bill", age: 35, email: "bill@company.com" }, - { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" } + { ssn: "555-55-5555", name: "Donna", age: 32, email: "donna@home.org" }, ]; ``` @@ -179,10 +189,10 @@ const dbName = "the_name"; var request = indexedDB.open(dbName, 2); -request.onerror = function(event) { +request.onerror = function (event) { // 错误处理 }; -request.onupgradeneeded = function(event) { +request.onupgradeneeded = function (event) { var db = event.target.result; // 建立一个对象仓库来存储我们客户的相关信息,我们选择 ssn 作为键路径(key path) @@ -196,10 +206,12 @@ request.onupgradeneeded = function(event) { objectStore.createIndex("email", "email", { unique: true }); // 使用事务的 oncomplete 事件确保在插入数据前对象仓库已经创建完毕 - objectStore.transaction.oncomplete = function(event) { + objectStore.transaction.oncomplete = function (event) { // 将数据保存到新创建的对象仓库 - var customerObjectStore = db.transaction("customers", "readwrite").objectStore("customers"); - customerData.forEach(function(customer) { + var customerObjectStore = db + .transaction("customers", "readwrite") + .objectStore("customers"); + customerData.forEach(function (customer) { customerObjectStore.add(customer); }); }; @@ -227,19 +239,18 @@ request.onupgradeneeded = function(event) { var request = indexedDB.open(dbName, 3); request.onupgradeneeded = function (event) { + var db = event.target.result; - var db = event.target.result; - - // 设置 autoIncrement 标志为 true 来创建一个名为 names 的对象仓库 - var objStore = db.createObjectStore("names", { autoIncrement : true }); + // 设置 autoIncrement 标志为 true 来创建一个名为 names 的对象仓库 + var objStore = db.createObjectStore("names", { autoIncrement: true }); - // 因为 names 对象仓库拥有键生成器,所以它的键会自动生成。 - // 被插入的数据可以表示如下: - // key : 1 => value : "Bill" - // key : 2 => value : "Donna" - customerData.forEach(function(customer) { - objStore.add(customer.name); - }); + // 因为 names 对象仓库拥有键生成器,所以它的键会自动生成。 + // 被插入的数据可以表示如下: + // key : 1 => value : "Bill" + // key : 2 => value : "Donna" + customerData.forEach(function (customer) { + objStore.add(customer.name); + }); }; ``` @@ -281,18 +292,18 @@ var transaction = db.transaction(["customers"], "readwrite"); ```js // 在所有数据添加完毕后的处理 -transaction.oncomplete = function(event) { +transaction.oncomplete = function (event) { alert("All done!"); }; -transaction.onerror = function(event) { +transaction.onerror = function (event) { // 不要忘记错误处理! }; var objectStore = transaction.objectStore("customers"); -customerData.forEach(function(customer) { +customerData.forEach(function (customer) { var request = objectStore.add(customer); - request.onsuccess = function(event) { + request.onsuccess = function (event) { // event.target.result === customer.ssn; }; }); @@ -305,10 +316,11 @@ customerData.forEach(function(customer) { 删除数据是非常类似的: ```js -var request = db.transaction(["customers"], "readwrite") - .objectStore("customers") - .delete("444-44-4444"); -request.onsuccess = function(event) { +var request = db + .transaction(["customers"], "readwrite") + .objectStore("customers") + .delete("444-44-4444"); +request.onsuccess = function (event) { // 删除成功! }; ``` @@ -321,10 +333,10 @@ request.onsuccess = function(event) { var transaction = db.transaction(["customers"]); var objectStore = transaction.objectStore("customers"); var request = objectStore.get("444-44-4444"); -request.onerror = function(event) { +request.onerror = function (event) { // 错误处理! }; -request.onsuccess = function(event) { +request.onsuccess = function (event) { // 对 request.result 做些操作! alert("Name for SSN 444-44-4444 is " + request.result.name); }; @@ -333,7 +345,10 @@ request.onsuccess = function(event) { 对于一个“简单”的提取这里的代码有点多了。下面看我们怎么把它再缩短一点,假设你在数据库的级别上来进行的错误处理: ```js -db.transaction("customers").objectStore("customers").get("444-44-4444").onsuccess = function(event) { +db + .transaction("customers") + .objectStore("customers") + .get("444-44-4444").onsuccess = function (event) { alert("Name for SSN 444-44-4444 is " + event.target.result.name); }; ``` @@ -350,12 +365,14 @@ db.transaction("customers").objectStore("customers").get("444-44-4444").onsucces 现在我们已经去除了一些数据,修改一下并把它插回数据库的操作时非常简单的。让我们来稍微更新一下上例中的数据。 ```js -var objectStore = db.transaction(["customers"], "readwrite").objectStore("customers"); +var objectStore = db + .transaction(["customers"], "readwrite") + .objectStore("customers"); var request = objectStore.get("444-44-4444"); -request.onerror = function(event) { +request.onerror = function (event) { // 错误处理 }; -request.onsuccess = function(event) { +request.onsuccess = function (event) { // 获取我们想要更新的数据 var data = event.target.result; @@ -364,12 +381,12 @@ request.onsuccess = function(event) { // 把更新过的对象放回数据库 var requestUpdate = objectStore.put(data); - requestUpdate.onerror = function(event) { - // 错误处理 - }; - requestUpdate.onsuccess = function(event) { - // 完成,数据已更新! - }; + requestUpdate.onerror = function (event) { + // 错误处理 + }; + requestUpdate.onsuccess = function (event) { + // 完成,数据已更新! + }; }; ``` @@ -384,13 +401,12 @@ request.onsuccess = function(event) { ```js var objectStore = db.transaction("customers").objectStore("customers"); -objectStore.openCursor().onsuccess = function(event) { +objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { alert("Name for SSN " + cursor.key + " is " + cursor.value.name); cursor.continue(); - } - else { + } else { alert("No more entries!"); } }; @@ -403,13 +419,12 @@ objectStore.openCursor().onsuccess = function(event) { ```js var customers = []; -objectStore.openCursor().onsuccess = function(event) { +objectStore.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { customers.push(cursor.value); cursor.continue(); - } - else { + } else { alert("以获取所有客户信息:" + customers); } }; @@ -418,7 +433,7 @@ objectStore.openCursor().onsuccess = function(event) { > **备注:** 可选地,你可以使用 `getAll()` 来处理这种情况(以及 `getAllKeys()`)。下面的代码的效果和上例相同: > > ```js -> objectStore.getAll().onsuccess = function(event) { +> objectStore.getAll().onsuccess = function (event) { > alert("Got all customers: " + event.target.result); > }; > ``` @@ -436,7 +451,7 @@ objectStore.openCursor().onsuccess = function(event) { var index = objectStore.index("name"); -index.get("Donna").onsuccess = function(event) { +index.get("Donna").onsuccess = function (event) { alert("Donna's SSN is " + event.target.result.ssn); }; ``` @@ -446,16 +461,23 @@ index.get("Donna").onsuccess = function(event) { 如果你需要访问带有给定 `name` 的所有的记录你可以使用一个游标。你可以在索引上打开两个不同类型的游标。一个常规游标映射索引属性到对象存储空间中的对象。一个键索引映射索引属性到用来存储对象存储空间中的对象的键。不同之处被展示如下: ```js -index.openCursor().onsuccess = function(event) { +index.openCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // cursor.key 是一个 name,就像 "Bill", 然后 cursor.value 是整个对象。 - alert("Name: " + cursor.key + ", SSN: " + cursor.value.ssn + ", email: " + cursor.value.email); + alert( + "Name: " + + cursor.key + + ", SSN: " + + cursor.value.ssn + + ", email: " + + cursor.value.email, + ); cursor.continue(); } }; -index.openKeyCursor().onsuccess = function(event) { +index.openKeyCursor().onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // cursor.key 是一个 name,就像 "Bill", 然后 cursor.value 是那个 SSN。 @@ -487,7 +509,7 @@ var upperBoundOpenKeyRange = IDBKeyRange.upperBound("Donna", true); var boundKeyRange = IDBKeyRange.bound("Bill", "Donna", false, true); // 使用其中的一个键范围,把它作为 openCursor()/openKeyCursor 的第一个参数 -index.openCursor(boundKeyRange).onsuccess = function(event) { +index.openCursor(boundKeyRange).onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // 当匹配时进行一些操作 @@ -499,7 +521,7 @@ index.openCursor(boundKeyRange).onsuccess = function(event) { 有时候你可能想要以倒序而不是正序(所有游标的默认顺序)来遍历。切换方向是通过传递 `prev` 到 `openCursor()` 方法来实现的: ```js -objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) { +objectStore.openCursor(boundKeyRange, "prev").onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // 进行一些操作 @@ -511,7 +533,7 @@ objectStore.openCursor(boundKeyRange, "prev").onsuccess = function(event) { 如果你只是想改变遍历的方向,而不想对结果进行筛选,你只需要给第一个参数传入 null。 ```js -objectStore.openCursor(null, "prev").onsuccess = function(event) { +objectStore.openCursor(null, "prev").onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // Do something with the entries. @@ -523,7 +545,7 @@ objectStore.openCursor(null, "prev").onsuccess = function(event) { 因为“name”索引不是唯一的,那就有可能存在具有相同 `name` 的多条记录。要注意的是这种情况不可能发生在对象存储空间上,因为键必须永远是唯一的。如果你想要在游标在索引迭代过程中过滤出重复的,你可以传递 `nextunique` (或 `prevunique` 如果你正在向后寻找)作为方向参数。当 `nextunique` 或是 `prevunique` 被使用时,被返回的那个总是键最小的记录。 ```js -index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function(event) { +index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function (event) { var cursor = event.target.result; if (cursor) { // Do something with the entries. @@ -541,18 +563,18 @@ index.openKeyCursor(null, IDBCursor.nextunique).onsuccess = function(event) { ```js var openReq = mozIndexedDB.open("MyTestDatabase", 2); -openReq.onblocked = function(event) { +openReq.onblocked = function (event) { // 如果其他的一些页签加载了该数据库,在我们继续之前需要关闭它们 alert("请关闭其他由该站点打开的页签!"); }; -openReq.onupgradeneeded = function(event) { +openReq.onupgradeneeded = function (event) { // 其他的数据已经被关闭,一切就绪 db.createObjectStore(/* ... */); useDatabase(db); }; -openReq.onsuccess = function(event) { +openReq.onsuccess = function (event) { var db = event.target.result; useDatabase(db); return; @@ -561,9 +583,11 @@ openReq.onsuccess = function(event) { function useDatabase(db) { // 当由其他页签请求了版本变更时,确认添加了一个会被通知的事件处理程序。 // 这里允许其他页签来更新数据库,如果不这样做,版本升级将不会发生知道用户关闭了这些页签。 - db.onversionchange = function(event) { + db.onversionchange = function (event) { db.close(); - alert("A new version of this page is ready. Please reload or close this tab!"); + alert( + "A new version of this page is ready. Please reload or close this tab!", + ); }; // 处理数据库 @@ -624,137 +648,132 @@ Mozilla 已经在 Firefox 43+ 中实现了对 IndexedDB 数据进行地区化排 ### HTML 内容 ```html - - -

    IndexedDB Demo: storing blobs, e-publication example

    -
    -

    - Works and tested with: -

    -
    -
    -
    - -
    -
    - -
    - - - - - - - - - - - - - - - - - - - - - - - - - -
    - - - -
    - - - -
    - - - -
    - - - -
    - - - -
    - -
    - - -
    -
    - -
    - - - - - - - - - - - -
    - - - -
    - - - -
    -
    - - -
    -
    - -
    -
    - -
    -
    - -
    -
    -
    -
    -
    -
      -
    -
    + + +

    IndexedDB Demo: storing blobs, e-publication example

    +
    +

    Works and tested with:

    +
    +
    + +
    + +
    + + + + + + + + + + + + + + + + + + + + + + + + + +
    + + + +
    + + + +
    + + + +
    + + + +
    + + + +
    + +
    + + +
    +
    + +
    + + + + + + + + + + + +
    + + + +
    + + + +
    +
    + + +
    +
    + +
    +
    + +
    +
    + +
    +
    +
    +
      +
      ``` ### CSS 内容 @@ -852,20 +871,22 @@ input { ```js (function () { var COMPAT_ENVS = [ - ['Firefox', ">= 16.0"], - ['Google Chrome', - ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support"] + ["Firefox", ">= 16.0"], + [ + "Google Chrome", + ">= 24.0 (you may need to get Google Chrome Canary), NO Blob storage support", + ], ]; - var compat = $('#compat'); + var compat = $("#compat"); compat.empty(); compat.append('
        '); - COMPAT_ENVS.forEach(function(val, idx, array) { - $('#compat-list').append('
      • ' + val[0] + ': ' + val[1] + '
      • '); + COMPAT_ENVS.forEach(function (val, idx, array) { + $("#compat-list").append("
      • " + val[0] + ": " + val[1] + "
      • "); }); - const DB_NAME = 'mdn-demo-indexeddb-epublications'; + const DB_NAME = "mdn-demo-indexeddb-epublications"; const DB_VERSION = 1; // Use a long long for this value (don't use a float) - const DB_STORE_NAME = 'publications'; + const DB_STORE_NAME = "publications"; var db; @@ -888,12 +909,14 @@ input { req.onupgradeneeded = function (evt) { console.log("openDb.onupgradeneeded"); - var store = evt.currentTarget.result.createObjectStore( - DB_STORE_NAME, { keyPath: 'id', autoIncrement: true }); - - store.createIndex('biblioid', 'biblioid', { unique: true }); - store.createIndex('title', 'title', { unique: false }); - store.createIndex('year', 'year', { unique: false }); + var store = evt.currentTarget.result.createObjectStore(DB_STORE_NAME, { + keyPath: "id", + autoIncrement: true, + }); + + store.createIndex("biblioid", "biblioid", { unique: true }); + store.createIndex("title", "title", { unique: false }); + store.createIndex("year", "year", { unique: false }); }; } @@ -907,9 +930,9 @@ input { } function clearObjectStore(store_name) { - var store = getObjectStore(DB_STORE_NAME, 'readwrite'); + var store = getObjectStore(DB_STORE_NAME, "readwrite"); var req = store.clear(); - req.onsuccess = function(evt) { + req.onsuccess = function (evt) { displayActionSuccess("Store cleared"); displayPubList(store); }; @@ -921,10 +944,9 @@ input { function getBlob(key, store, success_callback) { var req = store.get(key); - req.onsuccess = function(evt) { + req.onsuccess = function (evt) { var value = evt.target.result; - if (value) - success_callback(value.blob); + if (value) success_callback(value.blob); }; } @@ -934,12 +956,12 @@ input { function displayPubList(store) { console.log("displayPubList"); - if (typeof store == 'undefined') - store = getObjectStore(DB_STORE_NAME, 'readonly'); + if (typeof store == "undefined") + store = getObjectStore(DB_STORE_NAME, "readonly"); - var pub_msg = $('#pub-msg'); + var pub_msg = $("#pub-msg"); pub_msg.empty(); - var pub_list = $('#pub-list'); + var pub_list = $("#pub-list"); pub_list.empty(); // Resetting the iframe so that it doesn't display previous content newViewerFrame(); @@ -950,18 +972,21 @@ input { // transaction, and their results are returned in the same order. // Thus the count text below will be displayed before the actual pub list // (not that it is algorithmically important in this case). - req.onsuccess = function(evt) { - pub_msg.append('

        There are ' + evt.target.result + - ' record(s) in the object store.

        '); + req.onsuccess = function (evt) { + pub_msg.append( + "

        There are " + + evt.target.result + + " record(s) in the object store.

        ", + ); }; - req.onerror = function(evt) { + req.onerror = function (evt) { console.error("add error", this.error); displayActionFailure(this.error); }; var i = 0; req = store.openCursor(); - req.onsuccess = function(evt) { + req.onsuccess = function (evt) { var cursor = evt.target.result; // If the cursor is pointing at something, ask for the data @@ -970,21 +995,31 @@ input { req = store.get(cursor.key); req.onsuccess = function (evt) { var value = evt.target.result; - var list_item = $('
      • ' + - '[' + cursor.key + '] ' + - '(biblioid: ' + value.biblioid + ') ' + - value.title + - '
      • '); - if (value.year != null) - list_item.append(' - ' + value.year); - - if (value.hasOwnProperty('blob') && - typeof value.blob != 'undefined') { + var list_item = $( + "
      • " + + "[" + + cursor.key + + "] " + + "(biblioid: " + + value.biblioid + + ") " + + value.title + + "
      • ", + ); + if (value.year != null) list_item.append(" - " + value.year); + + if ( + value.hasOwnProperty("blob") && + typeof value.blob != "undefined" + ) { var link = $('File'); - link.on('click', function() { return false; }); - link.on('mouseenter', function(evt) { - setInViewer(evt.target.getAttribute('href')); }); - list_item.append(' / '); + link.on("click", function () { + return false; + }); + link.on("mouseenter", function (evt) { + setInViewer(evt.target.getAttribute("href")); + }); + list_item.append(" / "); list_item.append(link); } else { list_item.append(" / No attached file"); @@ -1004,9 +1039,9 @@ input { } function newViewerFrame() { - var viewer = $('#pub-viewer'); + var viewer = $("#pub-viewer"); viewer.empty(); - var iframe = $(' + diff --git a/files/zh-cn/web/javascript/reference/errors/read-only/index.md b/files/zh-cn/web/javascript/reference/errors/read-only/index.md index 3d84514a8c2f85..c52a8e82203eac 100644 --- a/files/zh-cn/web/javascript/reference/errors/read-only/index.md +++ b/files/zh-cn/web/javascript/reference/errors/read-only/index.md @@ -56,19 +56,19 @@ Math.PI = 4; // TypeError ```js example-bad "use strict"; -undefined = function () {}; // TypeError: "undefined" is read-only +undefined = function () {}; // TypeError: "undefined" is read-only ``` ### 下面这样都是有效,不报错的 ```js example-good "use strict"; -var obj = Object.freeze({name: "Score", points: 157}); -obj = {name: obj.name, points: 0}; // 用一个新对象替换原来的对象 (其实就是更改了对象的指针) +var obj = Object.freeze({ name: "Score", points: 157 }); +obj = { name: obj.name, points: 0 }; // 用一个新对象替换原来的对象 (其实就是更改了对象的指针) -"use strict"; -var LUNG_COUNT = 2; // -LUNG_COUNT = 3; // +("use strict"); +var LUNG_COUNT = 2; // +LUNG_COUNT = 3; // ``` ## 参见 diff --git a/files/zh-cn/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.md b/files/zh-cn/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.md index f151f842c6c69f..bbb8444c3dfd06 100644 --- a/files/zh-cn/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.md +++ b/files/zh-cn/web/javascript/reference/errors/reduce_of_empty_array_with_no_initial_value/index.md @@ -1,5 +1,5 @@ --- -title: 'TypeError: Reduce of empty array with no initial value' +title: "TypeError: Reduce of empty array with no initial value" slug: Web/JavaScript/Reference/Errors/Reduce_of_empty_array_with_no_initial_value --- @@ -32,15 +32,19 @@ TypeError: reduce of empty array with no initial value ```js example-bad var ints = [0, -1, -2, -3, -4, -5]; -ints.filter(x => x > 0) // removes all elements - .reduce((x, y) => x + y) // no more elements to use for the initial value. +ints + .filter((x) => x > 0) // removes all elements + .reduce((x, y) => x + y); // no more elements to use for the initial value. ``` 类似的,当选择器中有瑕疵的时候相同的问题会发生,或者是列表中未预期的数量的元素: ```js example-bad var names = document.getElementsByClassName("names"); -var name_list = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); +var name_list = Array.prototype.reduce.call( + names, + (acc, name) => acc + ", " + name, +); ``` ### 有效的情况 @@ -51,8 +55,9 @@ var name_list = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + n ```js example-good var ints = [0, -1, -2, -3, -4, -5]; -ints.filter(x => x < 0) // removes all elements - .reduce((x, y) => x + y, 0) // the initial value is the neutral element of the addition +ints + .filter((x) => x < 0) // removes all elements + .reduce((x, y) => x + y, 0); // the initial value is the neutral element of the addition ``` 另一种办法是两方处理空的情况,要么在调用 `reduce` 之前,或者是在添加一个未预料的初始虚拟址后的回调函数中: @@ -62,14 +67,22 @@ var names = document.getElementsByClassName("names"); var name_list1 = ""; if (names1.length >= 1) - name_list1 = Array.prototype.reduce.call(names, (acc, name) => acc + ", " + name); + name_list1 = Array.prototype.reduce.call( + names, + (acc, name) => acc + ", " + name, + ); // name_list1 == "" when names is empty. -var name_list2 = Array.prototype.reduce.call(names, (acc, name) => { - if (acc == "") // initial value - return name; - return acc + ", " + name; -}, ""); +var name_list2 = Array.prototype.reduce.call( + names, + (acc, name) => { + if (acc == "") + // initial value + return name; + return acc + ", " + name; + }, + "", +); // name_list2 == "" when names is empty. ``` diff --git a/files/zh-cn/web/javascript/reference/errors/resulting_string_too_large/index.md b/files/zh-cn/web/javascript/reference/errors/resulting_string_too_large/index.md index 6486bb9afcd8f0..0031543d366830 100644 --- a/files/zh-cn/web/javascript/reference/errors/resulting_string_too_large/index.md +++ b/files/zh-cn/web/javascript/reference/errors/resulting_string_too_large/index.md @@ -1,5 +1,5 @@ --- -title: 'RangeError: repeat count must be less than infinity' +title: "RangeError: repeat count must be less than infinity" slug: Web/JavaScript/Reference/Errors/Resulting_string_too_large --- @@ -28,17 +28,17 @@ RangeError: Invalid count value (Chrome) ### 无效的 ```js example-bad -'abc'.repeat(Infinity); // RangeError -'a'.repeat(2**28); // RangeError +"abc".repeat(Infinity); // RangeError +"a".repeat(2 ** 28); // RangeError ``` ### 有效的 ```js example-good -'abc'.repeat(0); // '' -'abc'.repeat(1); // 'abc' -'abc'.repeat(2); // 'abcabc' -'abc'.repeat(3.5); // 'abcabcabc' (count will be converted to integer) +"abc".repeat(0); // '' +"abc".repeat(1); // 'abc' +"abc".repeat(2); // 'abcabc' +"abc".repeat(3.5); // 'abcabcabc' (count will be converted to integer) ``` ## See also diff --git a/files/zh-cn/web/javascript/reference/errors/stmt_after_return/index.md b/files/zh-cn/web/javascript/reference/errors/stmt_after_return/index.md index 982da8d02d3d2f..55009fea43ace4 100644 --- a/files/zh-cn/web/javascript/reference/errors/stmt_after_return/index.md +++ b/files/zh-cn/web/javascript/reference/errors/stmt_after_return/index.md @@ -1,5 +1,5 @@ --- -title: 'Warning: unreachable code after return statement' +title: "Warning: unreachable code after return statement" slug: Web/JavaScript/Reference/Errors/Stmt_after_return --- @@ -43,13 +43,13 @@ Warning: unreachable code after return statement (Firefox) function f() { let x = 3; x += 4; - return x; // return 语句立即退出当前方法 - x -= 3; // 因而该语句从不会执行,即该语句为不可达语句 + return x; // return 语句立即退出当前方法 + x -= 3; // 因而该语句从不会执行,即该语句为不可达语句 } function f() { - return // 这条语句被视作 `return;` - 3 + 4; // 因而此处该函数已经返回,该语句永不会执行 + return; // 这条语句被视作 `return;` + 3 + 4; // 因而此处该函数已经返回,该语句永不会执行 } ``` @@ -60,11 +60,11 @@ function f() { let x = 3; x += 4; x -= 3; - return x; // OK: 执行完成所有语句之后返回 + return x; // OK: 执行完成所有语句之后返回 } function f() { - return 3 + 4 // OK: 省略分号的 return 语句与执行的表达式在同一行 + return 3 + 4; // OK: 省略分号的 return 语句与执行的表达式在同一行 } ``` diff --git a/files/zh-cn/web/javascript/reference/errors/strict_non_simple_params/index.md b/files/zh-cn/web/javascript/reference/errors/strict_non_simple_params/index.md index 89ba9fe08d9d66..669565455693ac 100644 --- a/files/zh-cn/web/javascript/reference/errors/strict_non_simple_params/index.md +++ b/files/zh-cn/web/javascript/reference/errors/strict_non_simple_params/index.md @@ -49,7 +49,7 @@ function sum(a=1, b=2) { ```js example-good "use strict"; -function sum(a=1, b=2) { +function sum(a = 1, b = 2) { return a + b; } ``` @@ -69,7 +69,7 @@ var sum = function sum([a, b]) { 这可以转换为以下表达式: ```js example-good -var sum = (function() { +var sum = (function () { "use strict"; return function sum([a, b]) { return a + b; diff --git a/files/zh-cn/web/javascript/reference/errors/too_much_recursion/index.md b/files/zh-cn/web/javascript/reference/errors/too_much_recursion/index.md index 7c0d5b7f3fe504..b9869b66f814d3 100644 --- a/files/zh-cn/web/javascript/reference/errors/too_much_recursion/index.md +++ b/files/zh-cn/web/javascript/reference/errors/too_much_recursion/index.md @@ -1,5 +1,5 @@ --- -title: 'InternalError: too much recursion' +title: "InternalError: too much recursion" slug: Web/JavaScript/Reference/Errors/Too_much_recursion --- @@ -25,8 +25,10 @@ InternalError: too much recursion ```js function loop(x) { - if (x >= 10) // "x >= 10" 是递归终止条件 + if (x >= 10) { + // "x >= 10" 是递归终止条件 return; + } // 进行一些操作... loop(x + 1); // 递归调用 } @@ -37,8 +39,9 @@ loop(0); ```js example-bad function loop(x) { - if (x >= 1000000000000) + if (x >= 1000000000000) { return; + } // 进行一些操作... loop(x + 1); } diff --git a/files/zh-cn/web/javascript/reference/errors/unexpected_token/index.md b/files/zh-cn/web/javascript/reference/errors/unexpected_token/index.md index d474d3791b9ade..674baa6a92a3e0 100644 --- a/files/zh-cn/web/javascript/reference/errors/unexpected_token/index.md +++ b/files/zh-cn/web/javascript/reference/errors/unexpected_token/index.md @@ -1,5 +1,5 @@ --- -title: 'SyntaxError: Unexpected token' +title: "SyntaxError: Unexpected token" slug: Web/JavaScript/Reference/Errors/Unexpected_token --- @@ -30,7 +30,7 @@ SyntaxError: expected '=>' after argument list, got "x" 例如,在调用函数时,不允许使用尾随逗号。有尾逗号的时候,JavaScript 会期望有另一个参数,可以是任何表达式。 -```js example-bad +```js-nolint example-bad Math.max(2, 42,); // SyntaxError: expected expression, got ')' ``` @@ -39,7 +39,7 @@ Math.max(2, 42,); ```js example-good Math.max(2, 42); -Math.max(2, 42, 13+37); +Math.max(2, 42, 13 + 37); ``` ## 相关 diff --git a/files/zh-cn/web/javascript/reference/errors/unexpected_type/index.md b/files/zh-cn/web/javascript/reference/errors/unexpected_type/index.md index 7eba7193d39816..1ebad722ee14e4 100644 --- a/files/zh-cn/web/javascript/reference/errors/unexpected_type/index.md +++ b/files/zh-cn/web/javascript/reference/errors/unexpected_type/index.md @@ -42,10 +42,10 @@ const foo = null; foo.substring(1); // TypeError: foo is null // Certain methods might require a specific type -const foo = {} +const foo = {}; Symbol.keyFor(foo); // TypeError: foo is not a symbol -const foo = 'bar' +const foo = "bar"; Object.create(foo); // TypeError: "foo" is not an object or null ``` diff --git a/files/zh-cn/web/javascript/reference/errors/unnamed_function_statement/index.md b/files/zh-cn/web/javascript/reference/errors/unnamed_function_statement/index.md index c9f760636d5306..69e7add77eebbc 100644 --- a/files/zh-cn/web/javascript/reference/errors/unnamed_function_statement/index.md +++ b/files/zh-cn/web/javascript/reference/errors/unnamed_function_statement/index.md @@ -1,5 +1,5 @@ --- -title: 'SyntaxError: function statement requires a name' +title: "SyntaxError: function statement requires a name" slug: Web/JavaScript/Reference/Errors/Unnamed_function_statement --- @@ -36,17 +36,15 @@ function () { 你可以使用[函数表达式](/zh-CN/docs/Web/JavaScript/Reference/Operators/function)(赋值)来代替: ```js example-good -var greet = function() { - return 'Hello world'; +var greet = function () { + return "Hello world"; }; ``` 者是你想将其作为立即调用函数表达式([IIFE](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression),Immediately Invoked Function Expression),也就是定义后立即执行的函数。在这种情况下你需要用到更多的括号: ```js example-good -(function () { - -})(); +(function () {})(); ``` ### 标号函数 (Labeled functions) @@ -80,7 +78,7 @@ function Greeter() { var greeter = { german: function () { return "Moin"; - } + }, }; ``` diff --git a/files/zh-cn/web/javascript/reference/errors/unterminated_string_literal/index.md b/files/zh-cn/web/javascript/reference/errors/unterminated_string_literal/index.md index 831e3f77733bd9..6eeaf33fecba4f 100644 --- a/files/zh-cn/web/javascript/reference/errors/unterminated_string_literal/index.md +++ b/files/zh-cn/web/javascript/reference/errors/unterminated_string_literal/index.md @@ -1,5 +1,5 @@ --- -title: 'SyntaxError: unterminated string literal' +title: "SyntaxError: unterminated string literal" slug: Web/JavaScript/Reference/Errors/Unterminated_string_literal --- @@ -39,15 +39,17 @@ var longString = "This is a very long string which needs 可以使用["+"运算符](/zh-CN/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Addition),反斜杠,或[模板字符串](/zh-CN/docs/Web/JavaScript/Reference/Template_literals)来代替多行。“+”运算符的使用如下: ```js example-good -var longString = "This is a very long string which needs " + - "to wrap across multiple lines because " + - "otherwise my code is unreadable."; +var longString = + "This is a very long string which needs " + + "to wrap across multiple lines because " + + "otherwise my code is unreadable."; ``` 或者你可以使用“\”在每一行的末尾,以表示该字符串在下一行继续。要确保“\“之后没有没有空格和任何其他的字符,及缩进,否则该“\”将不会起作用。使用方法如下: ```js example-good -var longString = "This is a very long string which needs \ +var longString = + "This is a very long string which needs \ to wrap across multiple lines because \ otherwise my code is unreadable."; ``` diff --git a/files/zh-cn/web/javascript/reference/functions/arguments/@@iterator/index.md b/files/zh-cn/web/javascript/reference/functions/arguments/@@iterator/index.md index 59fa68c01edc1f..def4e022c707ce 100644 --- a/files/zh-cn/web/javascript/reference/functions/arguments/@@iterator/index.md +++ b/files/zh-cn/web/javascript/reference/functions/arguments/@@iterator/index.md @@ -25,7 +25,7 @@ function f() { console.log(letter); } } -f('w', 'y', 'k', 'o', 'p'); +f("w", "y", "k", "o", "p"); ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/functions/arguments/callee/index.md b/files/zh-cn/web/javascript/reference/functions/arguments/callee/index.md index 872423dad0992c..d600f5d5dd4eba 100644 --- a/files/zh-cn/web/javascript/reference/functions/arguments/callee/index.md +++ b/files/zh-cn/web/javascript/reference/functions/arguments/callee/index.md @@ -22,26 +22,26 @@ slug: Web/JavaScript/Reference/Functions/arguments/callee 例如,下边这个语法就是行的通的: ```js -function factorial (n) { - return !(n > 1) ? 1 : factorial(n - 1) * n; +function factorial(n) { + return !(n > 1) ? 1 : factorial(n - 1) * n; } -[1,2,3,4,5].map(factorial); +[1, 2, 3, 4, 5].map(factorial); ``` 但是: ```js -[1,2,3,4,5].map(function (n) { - return !(n > 1) ? 1 : /* what goes here? */ (n - 1) * n; +[1, 2, 3, 4, 5].map(function (n) { + return !(n > 1) ? 1 : /* what goes here? */ (n - 1) * n; }); ``` 这个不行。为了解决这个问题, `arguments.callee` 添加进来了。然后你可以这么做 ```js -[1,2,3,4,5].map(function (n) { - return !(n > 1) ? 1 : arguments.callee(n - 1) * n; +[1, 2, 3, 4, 5].map(function (n) { + return !(n > 1) ? 1 : arguments.callee(n - 1) * n; }); ``` @@ -51,13 +51,15 @@ function factorial (n) { var global = this; var sillyFunction = function (recursed) { - if (!recursed) { return arguments.callee(true); } - if (this !== global) { - alert("This is: " + this); - } else { - alert("This is the global"); - } -} + if (!recursed) { + return arguments.callee(true); + } + if (this !== global) { + alert("This is: " + this); + } else { + alert("This is the global"); + } +}; sillyFunction(); ``` @@ -65,8 +67,8 @@ sillyFunction(); ECMAScript 3 通过允许命名函数表达式解决这些问题。例如: ```js -[1,2,3,4,5].map(function factorial (n) { - return !(n > 1) ? 1 : factorial(n-1)*n; +[1, 2, 3, 4, 5].map(function factorial(n) { + return !(n > 1) ? 1 : factorial(n - 1) * n; }); ``` @@ -79,7 +81,9 @@ ECMAScript 3 通过允许命名函数表达式解决这些问题。例如: 另外一个被废弃的特性是 `arguments.callee.caller`,具体点说则是 `Function.caller。为什么`? 额,在任何一个时间点,你能在堆栈中找到任何函数的最深层的调用者,也正如我在上面提到的,在调用堆栈有一个单一重大影响:不可能做大量的优化,或者有更多更多的困难。比如,如果你不能保证一个函数 f 不会调用一个未知函数,它就绝不可能是内联函数 f。基本上这意味着内联代码中积累了大量防卫代码: ```js -function f (a, b, c, d, e) { return a ? b * c : d * e; } +function f(a, b, c, d, e) { + return a ? b * c : d * e; +} ``` 如果 JavaScript 解释器不能保证所有提供的参数数量在被调用的时候都存在,那么它需要在行内代码插入检查,或者不能内联这个函数。现在在这个特殊例子里一个智能的解释器应该能重排检查而更优,并检查任何将不用到的值。然而在许多的情况里那是不可能的,也因此它不能够内联。 @@ -94,11 +98,10 @@ function f (a, b, c, d, e) { return a ? b * c : d * e; } ```js function create() { - return function(n) { - if (n <= 1) - return 1; - return n * arguments.callee(n - 1); - }; + return function (n) { + if (n <= 1) return 1; + return n * arguments.callee(n - 1); + }; } var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1) @@ -109,10 +112,10 @@ var result = create()(5); // returns 120 (5 * 4 * 3 * 2 * 1) 当你必须要使用 Function 构造函数时,下面的例子是没有可以替代 `arguments.callee` 的方案的,因此弃用它时会产生一个 BUG (参看 [Firefox bug 725398](https://bugzil.la/725398)): ```js -function createPerson (sIdentity) { - var oPerson = new Function("alert(arguments.callee.identity);"); - oPerson.identity = sIdentity; - return oPerson; +function createPerson(sIdentity) { + var oPerson = new Function("alert(arguments.callee.identity);"); + oPerson.identity = sIdentity; + return oPerson; } var john = createPerson("John Smith"); @@ -123,12 +126,12 @@ john(); 译者注:利用命名函数表达式也可以实现上述例子的同样效果 ```js -function createPerson (identity) { - function Person() { - console.log(Person.identity); - } - Person.identity = identity; - return Person; +function createPerson(identity) { + function Person() { + console.log(Person.identity); + } + Person.identity = identity; + return Person; } var john = createPerson("John Smith"); diff --git a/files/zh-cn/web/javascript/reference/functions/arguments/index.md b/files/zh-cn/web/javascript/reference/functions/arguments/index.md index ffdb4c5d69424e..bc6df8508351da 100644 --- a/files/zh-cn/web/javascript/reference/functions/arguments/index.md +++ b/files/zh-cn/web/javascript/reference/functions/arguments/index.md @@ -18,15 +18,15 @@ slug: Web/JavaScript/Reference/Functions/arguments `arguments`对象是所有(非箭头)函数中都可用的**局部变量**。你可以使用`arguments`对象在函数中引用函数的参数。此对象包含传递给函数的每个参数,第一个参数在索引 0 处。例如,如果一个函数传递了三个参数,你可以以如下方式引用他们: ```js -arguments[0] -arguments[1] -arguments[2] +arguments[0]; +arguments[1]; +arguments[2]; ``` 参数也可以被设置: ```js -arguments[1] = 'new value'; +arguments[1] = "new value"; ``` `arguments`对象不是一个 {{jsxref("Array")}} 。它类似于`Array`,但除了 length 属性和索引元素之外没有任何`Array`属性。例如,它没有 [pop](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/pop) 方法。但是它可以被转换为一个真正的`Array`: @@ -43,7 +43,8 @@ const args = [...arguments]; > **警告:** 对参数使用 slice 会阻止某些 JavaScript 引擎中的优化 (比如 V8 - [更多信息](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments))。如果你关心性能,尝试通过遍历 arguments 对象来构造一个新的数组。另一种方法是使用被忽视的`Array`构造函数作为一个函数: > > ```js -> var args = (arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments)); +> var args = +> arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); > ``` 如果调用的参数多于正式声明接受的参数,则可以使用`arguments`对象。这种技术对于可以传递可变数量的参数的函数很有用。使用 [`arguments.length`](/zh-CN/docs/JavaScript/Reference/Functions_and_function_scope/arguments/length)来确定传递给函数参数的个数,然后使用`arguments`对象来处理每个参数。要确定函数[签名](/zh-CN/docs/Glossary/Signature/Function)中(输入)参数的数量,请使用[`Function.length`](/zh-CN/docs/JavaScript/Reference/Global_Objects/Function/length)属性。 @@ -53,12 +54,12 @@ const args = [...arguments]; typeof 参数返回 'object'。 ```js -console.log(typeof arguments); // 'object' +console.log(typeof arguments); // 'object' // arguments 对象只能在函数内使用 -function test(a){ - console.log(a,Object.prototype.toString.call(arguments)); - console.log(arguments[0],arguments[1]); - console.log(typeof arguments[0]); +function test(a) { + console.log(a, Object.prototype.toString.call(arguments)); + console.log(arguments[0], arguments[1]); + console.log(typeof arguments[0]); } test(1); /* @@ -98,16 +99,16 @@ var args = [...arguments]; ```js function add() { - var sum =0, - len = arguments.length; - for(var i=0; i { }); // [8, 6, 7, 9] // 当箭头函数只有一个参数时,可以省略参数的圆括号 -elements.map(element => { - return element.length; +elements.map((element) => { + return element.length; }); // [8, 6, 7, 9] // 当箭头函数的函数体只有一个 `return` 语句时,可以省略 `return` 关键字和方法体的花括号 -elements.map(element => element.length); // [8, 6, 7, 9] +elements.map((element) => element.length); // [8, 6, 7, 9] // 在这个例子中,因为我们只需要 `length` 属性,所以可以使用参数解构 // 需要注意的是字符串 `"length"` 是我们想要获得的属性的名称,而 `lengthFooBArX` 则只是个变量名, // 可以替换成任意合法的变量名 -elements.map(({ "length": lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9] +elements.map(({ length: lengthFooBArX }) => lengthFooBArX); // [8, 6, 7, 9] ``` ### 没有单独的`this` @@ -126,7 +121,7 @@ function Person() { 箭头函数不会创建自己的`this,它只会从自己的作用域链的上一层继承 this`。因此,在下面的代码中,传递给`setInterval`的函数内的`this`与封闭函数中的`this`值相同: ```js -function Person(){ +function Person() { this.age = 0; setInterval(() => { @@ -154,24 +149,24 @@ f() === window; // 或者 global ```js var adder = { - base : 1, + base: 1, - add : function(a) { - var f = v => v + this.base; + add: function (a) { + var f = (v) => v + this.base; return f(a); }, - addThruCall: function(a) { - var f = v => v + this.base; + addThruCall: function (a) { + var f = (v) => v + this.base; var b = { - base : 2 + base: 2, }; return f.call(b, a); - } + }, }; -console.log(adder.add(1)); // 输出 2 +console.log(adder.add(1)); // 输出 2 console.log(adder.addThruCall(1)); // 仍然输出 2 ``` @@ -193,7 +188,7 @@ function foo(n) { foo(1); // 2 foo(2); // 4 foo(3); // 6 -foo(3,2);//6 +foo(3, 2); //6 ``` 在大多数情况下,使用[剩余参数](/zh-CN/docs/Web/JavaScript/Reference/Functions/Rest_parameters)是相较使用`arguments`对象的更好选择。 @@ -205,11 +200,11 @@ function foo(arg) { } foo(1); // 1 -function foo(arg1,arg2) { - var f = (...args) => args[1]; - return f(arg1,arg2); +function foo(arg1, arg2) { + var f = (...args) => args[1]; + return f(arg1, arg2); } -foo(1,2); //2 +foo(1, 2); //2 ``` ### 使用箭头函数作为方法 @@ -217,14 +212,14 @@ foo(1,2); //2 如上所述,箭头函数表达式对非方法函数是最合适的。让我们看看当我们试着把它们作为方法时发生了什么。 ```js -'use strict'; +"use strict"; var obj = { i: 10, b: () => console.log(this.i, this), - c: function() { - console.log( this.i, this) - } -} + c: function () { + console.log(this.i, this); + }, +}; obj.b(); // undefined, Window{...} obj.c(); @@ -234,17 +229,17 @@ obj.c(); 箭头函数没有定义 this 绑定。另一个涉及{{jsxref("Object.defineProperty()")}}的示例: ```js -'use strict'; +"use strict"; var obj = { - a: 10 + a: 10, }; Object.defineProperty(obj, "b", { get: () => { console.log(this.a, typeof this.a, this); - return this.a+10; - // 代表全局对象 'Window', 因此 'this.a' 返回 'undefined' - } + return this.a + 10; + // 代表全局对象 'Window', 因此 'this.a' 返回 'undefined' + }, }); obj.b; // undefined "undefined" Window {postMessage: ƒ, blur: ƒ, focus: ƒ, close: ƒ, frames: Window, …} @@ -279,10 +274,12 @@ console.log(Foo.prototype); // undefined 在一个简写体中,只需要一个表达式,并附加一个隐式的返回值。在块体中,必须使用明确的`return`语句。 ```js -var func = x => x * x; +var func = (x) => x * x; // 简写函数 省略 return -var func = (x, y) => { return x + y; }; +var func = (x, y) => { + return x + y; +}; //常规编写 明确的返回值 ``` @@ -303,7 +300,7 @@ var func = () => { foo: function() {} }; 所以,记得用圆括号把对象字面量包起来: ```js -var func = () => ({foo: 1}); +var func = () => ({ foo: 1 }); ``` ## 换行 @@ -319,22 +316,15 @@ var func = () 但是,可以通过在‘=>’之后换行,或者用‘( )’、'{ }'来实现换行,如下: ```js -var func = (a, b, c) => - 1; +var func = (a, b, c) => 1; -var func = (a, b, c) => ( - 1 -); +var func = (a, b, c) => 1; var func = (a, b, c) => { - return 1 + return 1; }; -var func = ( - a, - b, - c -) => 1; +var func = (a, b, c) => 1; // 不会有语法错误 ``` @@ -360,16 +350,15 @@ callback = callback || (() => {}); // ok // 空的箭头函数返回 undefined let empty = () => {}; -(() => 'foobar')(); +(() => "foobar")(); // Returns "foobar" // (这是一个立即执行函数表达式,可参阅 'IIFE'术语表) - -var simple = a => a > 15 ? 15 : a; +var simple = (a) => (a > 15 ? 15 : a); simple(16); // 15 simple(10); // 10 -let max = (a, b) => a > b ? a : b; +let max = (a, b) => (a > b ? a : b); // Easy array filtering, mapping, ... @@ -378,25 +367,27 @@ var arr = [5, 6, 13, 0, 1, 18, 23]; var sum = arr.reduce((a, b) => a + b); // 66 -var even = arr.filter(v => v % 2 == 0); +var even = arr.filter((v) => v % 2 == 0); // [6, 0, 18] -var double = arr.map(v => v * 2); +var double = arr.map((v) => v * 2); // [10, 12, 26, 0, 2, 36, 46] // 更简明的 promise 链 -promise.then(a => { - // ... -}).then(b => { - // ... -}); +promise + .then((a) => { + // ... + }) + .then((b) => { + // ... + }); // 无参数箭头函数在视觉上容易分析 -setTimeout( () => { - console.log('I happen sooner'); - setTimeout( () => { +setTimeout(() => { + console.log("I happen sooner"); + setTimeout(() => { // deeper code - console.log('I happen later'); + console.log("I happen later"); }, 1); }, 1); ``` @@ -404,68 +395,82 @@ setTimeout( () => { #### 箭头函数也可以使用条件(三元)运算符: ```js -var simple = a => a > 15 ? 15 : a; +var simple = (a) => (a > 15 ? 15 : a); simple(16); // 15 simple(10); // 10 -let max = (a, b) => a > b ? a : b; +let max = (a, b) => (a > b ? a : b); ``` > 箭头函数内定义的变量及其作用域 ```js // 常规写法 -var greeting = () => {let now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));} -greeting(); //"Good day." -console.log(now); // ReferenceError: now is not defined 标准的 let 作用域 +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 作用域 // 参数括号内定义的变量是局部变量(默认参数) -var greeting = (now=new Date()) => "Good" + (now.getHours() > 17 ? " evening." : " day."); -greeting(); //"Good day." -console.log(now); // ReferenceError: now is not defined +var greeting = (now = new Date()) => + "Good" + (now.getHours() > 17 ? " evening." : " day."); +greeting(); //"Good day." +console.log(now); // ReferenceError: now is not defined // 对比:函数体内{}不使用 var 定义的变量是全局变量 -var greeting = () => {now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));} -greeting(); //"Good day." -console.log(now); // Fri Dec 22 2017 10:01:00 GMT+0800 (中国标准时间) +var greeting = () => { + now = new Date(); + return "Good" + (now.getHours() > 17 ? " evening." : " day."); +}; +greeting(); //"Good day." +console.log(now); // Fri Dec 22 2017 10:01:00 GMT+0800 (中国标准时间) // 对比:函数体内{} 用 var 定义的变量是局部变量 -var greeting = () => {var now = new Date(); return ("Good" + ((now.getHours() > 17) ? " evening." : " day."));} +var greeting = () => { + var now = new Date(); + return "Good" + (now.getHours() > 17 ? " evening." : " day."); +}; greeting(); //"Good day." -console.log(now); // ReferenceError: now is not defined +console.log(now); // ReferenceError: now is not defined ``` > #### 箭头函数也可以使用闭包: ```js // 标准的闭包函数 -function A(){ - var i=0; - return function b(){ - return (++i); - }; -}; - -var v=A(); -v(); //1 -v(); //2 +function A() { + var i = 0; + return function b() { + return ++i; + }; +} +var v = A(); +v(); //1 +v(); //2 //箭头函数体的闭包(i=0 是默认参数) -var Add = (i=0) => {return (() => (++i) )}; +var Add = (i = 0) => { + return () => ++i; +}; var v = Add(); -v(); //1 -v(); //2 +v(); //1 +v(); //2 //因为仅有一个返回,return 及括号()也可以省略 -var Add = (i=0)=> ()=> (++i); +var Add = + (i = 0) => + () => + ++i; ``` > #### 箭头函数递归 ```js -var fact = (x) => ( x==0 ? 1 : x*fact(x-1) ); -fact(5); // 120 +var fact = (x) => (x == 0 ? 1 : x * fact(x - 1)); +fact(5); // 120 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/functions/default_parameters/index.md b/files/zh-cn/web/javascript/reference/functions/default_parameters/index.md index 3acb7095721a60..783934087612e4 100644 --- a/files/zh-cn/web/javascript/reference/functions/default_parameters/index.md +++ b/files/zh-cn/web/javascript/reference/functions/default_parameters/index.md @@ -31,19 +31,19 @@ function multiply(a, b) { } multiply(5, 2); // 10 -multiply(5); // NaN ! +multiply(5); // NaN ! ``` 为了防止这种情况,第二行代码解决了这个问题,其中如果只使用一个参数调用`multiply`,则`b`设置为`1`: ```js function multiply(a, b) { - b = (typeof b !== 'undefined') ? b : 1; + b = typeof b !== "undefined" ? b : 1; return a * b; } multiply(5, 2); // 10 -multiply(5); // 5 +multiply(5); // 5 ``` 有了默认参数,我们不需要再在函数体内做不必要的检查。现在你可以在函数头将`b`的默认值置为`1`: @@ -54,7 +54,7 @@ function multiply(a, b = 1) { } multiply(5, 2); // 10 -multiply(5); // 5 +multiply(5); // 5 ``` ## 示例 @@ -68,12 +68,12 @@ function test(num = 1) { console.log(typeof num); } -test(); // 'number' (num is set to 1) +test(); // 'number' (num is set to 1) test(undefined); // 'number' (num is set to 1 too) // test with other falsy values: -test(''); // 'string' (num is set to '') -test(null); // 'object' (num is set to null) +test(""); // 'string' (num is set to '') +test(null); // 'object' (num is set to null) ``` ### 调用时解析 @@ -94,7 +94,7 @@ append(2); //[2], not [1, 2] ```js function callSomething(thing = something()) { - return thing; + return thing; } let numberOfTimesCalled = 0; @@ -112,23 +112,30 @@ callSomething(); // 2 已经遇到的参数可用于以后的默认参数: ```js -function greet(name, greeting, message = greeting + ' ' + name) { - return [name, greeting, message]; +function greet(name, greeting, message = greeting + " " + name) { + return [name, greeting, message]; } -greet('David', 'Hi'); // ["David", "Hi", "Hi David"] -greet('David', 'Hi', 'Happy Birthday!'); // ["David", "Hi", "Happy Birthday!"] +greet("David", "Hi"); // ["David", "Hi", "Hi David"] +greet("David", "Hi", "Happy Birthday!"); // ["David", "Hi", "Happy Birthday!"] ``` 以下这个例子近似模拟了一些比较简单的情况,并说明了特殊情况是怎么被处理的。 ```js function go() { - return ':P'; + return ":P"; } -function withDefaults(a, b = 5, c = b, d = go(), e = this, - f = arguments, g = this.value) { +function withDefaults( + a, + b = 5, + c = b, + d = go(), + e = this, + f = arguments, + g = this.value, +) { return [a, b, c, d, e, f, g]; } @@ -153,11 +160,10 @@ function withoutDefaults(a, b, c, d, e, f, g) { return [a, b, c, d, e, f, g]; } -withDefaults.call({value: '=^_^='}); +withDefaults.call({ value: "=^_^=" }); // [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] - -withoutDefaults.call({value: '=^_^='}); +withoutDefaults.call({ value: "=^_^=" }); // [undefined, 5, 5, ":P", {value:"=^_^="}, arguments, "=^_^="] ``` @@ -168,7 +174,9 @@ withoutDefaults.call({value: '=^_^='}); ```js // Doesn't work! Throws ReferenceError. function f(a = go()) { - function go() { return ':P'; } + function go() { + return ":P"; + } } ``` @@ -190,7 +198,7 @@ f(2); // [2, undefined] 你可以通过[解构赋值](/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)为参数赋值: ```js -function f([x, y] = [1, 2], {z: z} = {z: 3}) { +function f([x, y] = [1, 2], { z: z } = { z: 3 }) { return x + y + z; } diff --git a/files/zh-cn/web/javascript/reference/functions/get/index.md b/files/zh-cn/web/javascript/reference/functions/get/index.md index 1b2446f3b2a195..0c949e999c4033 100644 --- a/files/zh-cn/web/javascript/reference/functions/get/index.md +++ b/files/zh-cn/web/javascript/reference/functions/get/index.md @@ -44,12 +44,12 @@ slug: Web/JavaScript/Reference/Functions/get ```js const obj = { - log: ['example','test'], + log: ["example", "test"], get latest() { if (this.log.length == 0) return undefined; return this.log[this.log.length - 1]; - } -} + }, +}; console.log(obj.latest); // "test". ``` @@ -68,20 +68,26 @@ delete obj.latest; 要随时将 getter 添加到现有对象,使用 {{jsxref("Object.defineProperty()")}}. ```js -var o = { a:0 } +var o = { a: 0 }; -Object.defineProperty(o, "b", { get: function () { return this.a + 1; } }); +Object.defineProperty(o, "b", { + get: function () { + return this.a + 1; + }, +}); -console.log(o.b) // Runs the getter, which yields a + 1 (which is 1) +console.log(o.b); // Runs the getter, which yields a + 1 (which is 1) ``` ### 使用计算出的属性名 ```js -var expr = 'foo'; +var expr = "foo"; var obj = { - get [expr]() { return 'bar'; } + get [expr]() { + return "bar"; + }, }; console.log(obj.foo); // "bar" @@ -119,7 +125,7 @@ get notifier() { ```js class Example { get hello() { - return 'world'; + return "world"; } } @@ -127,13 +133,11 @@ const obj = new Example(); console.log(obj.hello); // "world" -console.log(Object.getOwnPropertyDescriptor(obj, 'hello')); +console.log(Object.getOwnPropertyDescriptor(obj, "hello")); // undefined console.log( - Object.getOwnPropertyDescriptor( - Object.getPrototypeOf(obj), 'hello' - ) + Object.getOwnPropertyDescriptor(Object.getPrototypeOf(obj), "hello"), ); // { configurable: true, enumerable: false, get: function get hello() { return 'world'; }, set: undefined } ``` diff --git a/files/zh-cn/web/javascript/reference/functions/index.md b/files/zh-cn/web/javascript/reference/functions/index.md index e87eaec2f53299..c3dc3462250a1b 100644 --- a/files/zh-cn/web/javascript/reference/functions/index.md +++ b/files/zh-cn/web/javascript/reference/functions/index.md @@ -16,34 +16,33 @@ slug: Web/JavaScript/Reference/Functions 调用函数时,传递给函数的值被称为函数的实参(值传递),对应位置的函数参数名叫作形参。如果实参是一个包含原始值 (数字,字符串,布尔值) 的变量,则就算函数在内部改变了对应形参的值,返回后,该实参变量的值也不会改变。如果实参是一个对象引用,则对应形参会和该实参指向同一个对象。假如函数在内部改变了对应形参的值,返回后,实参指向的对象的值也会改变: ```js - /* 定义函数 myFunc */ - function myFunc(theObject) - { - //实参 mycar 和形参 theObject 指向同一个对象。 - theObject.brand = "Toyota"; - } - - /* - * 定义变量 mycar; - * 创建并初始化一个对象; - * 将对象的引用赋值给变量 mycar - */ - var mycar = { - brand: "Honda", - model: "Accord", - year: 1998 - }; - - /* 弹出 'Honda' */ - window.alert(mycar.brand); - - /* 将对象引用传给函数 */ - myFunc(mycar); - - /* - * 弹出 'Toyota',对象的属性已被修改。 - */ - console.log(mycar.brand); +/* 定义函数 myFunc */ +function myFunc(theObject) { + //实参 mycar 和形参 theObject 指向同一个对象。 + theObject.brand = "Toyota"; +} + +/* + * 定义变量 mycar; + * 创建并初始化一个对象; + * 将对象的引用赋值给变量 mycar + */ +var mycar = { + brand: "Honda", + model: "Accord", + year: 1998, +}; + +/* 弹出 'Honda' */ +window.alert(mycar.brand); + +/* 将对象引用传给函数 */ +myFunc(mycar); + +/* + * 弹出 'Toyota',对象的属性已被修改。 + */ +console.log(mycar.brand); ``` 在函数执行时,[`this` 关键字](/zh-CN/JavaScript/Reference/Operators/this)并不会指向正在运行的函数本身,而是指向调用该函数的对象。所以,如果你想在函数内部获取函数自身的引用,只能使用函数名或者使用[arguments.callee](/zh-CN/JavaScript/Reference/Functions_and_function_scope/arguments/callee)属性 (**[严格模式](/zh-CN/JavaScript/Strict_mode)**下不可用),如果该函数是一个匿名函数,则你只能使用后者。 @@ -85,17 +84,17 @@ var myFunction = function name([param[, param[, ... param]]]) { statements } 下面是**匿名**函数的一个例子(函数没有名字): ```js -var myFunction = function() { - // statements -} +var myFunction = function () { + // statements +}; ``` 也可以在定义时为函数**命名**: ```js -var myFunction = function namedFunction(){ - // statements -} +var myFunction = function namedFunction() { + // statements +}; ``` 命名函数表达式的好处是当我们遇到错误时,堆栈跟踪会显示函数名,容易寻找错误。 @@ -105,8 +104,8 @@ var myFunction = function namedFunction(){ 当函数只使用一次时,通常使用**IIFE (_Immediately Invokable Function Expressions_)。** ```js -(function() { - statements +(function () { + statements; })(); ``` @@ -226,10 +225,10 @@ new GeneratorFunction (arg1, arg2, ... argN, functionBody) 从 ECMAScript 6 开始,你可以用更短的语法定义自己的方法,类似于 getters 和 setters。详情请查阅 [method definitions](/zh-CN/docs/Web/JavaScript/Reference/Functions/Method_definitions) . ```js - var obj = { - foo() {}, - bar() {} - }; +var obj = { + foo() {}, + bar() {}, +}; ``` ## 构造函数 vs 函数声明 vs 函数表达式 @@ -239,30 +238,30 @@ new GeneratorFunction (arg1, arg2, ... argN, functionBody) 一个用`Function`构造函数定义的函数,被赋值给变量 multiply: ```js -var multiply = new Function('x', 'y', 'return x * y'); +var multiply = new Function("x", "y", "return x * y"); ``` 一个名为`multiply`的函数声明: ```js function multiply(x, y) { - return x * y; + return x * y; } // 没有分号 ``` 一个匿名函数的函数表达式,被赋值给变量`multiply`: ```js - var multiply = function(x, y) { - return x * y; - }; +var multiply = function (x, y) { + return x * y; +}; ``` 一个命名为`func_named`的函数的函数表达式,被赋值给变量`multiply`: ```js var multiply = function func_name(x, y) { - return x * y; + return x * y; }; ``` @@ -286,8 +285,7 @@ alert(x); // throws an error 使用用 '`new Function'定义的函数没有函数名。` 然而,在 [SpiderMonkey](/zh-CN/docs/Mozilla/Projects/SpiderMonkey) JavaScript 引擎中,其函数的序列化形式表现的好像它拥有一个名叫"anonymous"的名称一样。比如,使用 `alert(new Function())` 输出: ```js -function anonymous() { -} +function anonymous() {} ``` 而实际上其函数并没有名称,`anonymous` 不是一个可以在函数内被访问到的变量。例如,下面的例子将会导致错误: @@ -302,7 +300,7 @@ foo(); ```js foo(); // alerts FOO! function foo() { - alert('FOO!'); + alert("FOO!"); } ``` @@ -313,7 +311,9 @@ function foo() { 有一点应该要注意的,在通过解析 Function 构造函数字符串产生的函数里,内嵌的函数表达式和函数声明不会被重复解析。例如: ```js -var foo = (new Function("var bar = \'FOO!\';\nreturn(function() {\n\talert(bar);\n});"))(); +var foo = new Function( + "var bar = 'FOO!';\nreturn(function() {\n\talert(bar);\n});", +)(); foo(); // 函数体字符串"function() {\n\talert(bar);\n}"的这一部分不会被重复解析。 ``` @@ -323,18 +323,21 @@ foo(); // 函数体字符串"function() {\n\talert(bar);\n}"的这一部分不 - 不再是函数或者脚本自身的“源元素”(source element)。“源元素”是脚本或函数体中的非嵌套语句。 ```js -var x = 0; // source element -if (x === 0) { // source element - x = 10; // 非 source element - function boo() {} // 非 source element +var x = 0; // source element +if (x === 0) { + // source element + x = 10; // 非 source element + function boo() {} // 非 source element } -function foo() { // source element - var y = 20; // source element - function bar() {} // source element - while (y === 10) { // source element - function blah() {} // 非 source element - y++; //非 source element - } +function foo() { + // source element + var y = 20; // source element + function bar() {} // source element + while (y === 10) { + // source element + function blah() {} // 非 source element + y++; //非 source element + } } ``` @@ -345,24 +348,24 @@ function foo() { // source element function foo() {} // 函数表达式 -(function bar() {}) +(function bar() {}); // 函数表达式 -x = function hello() {} +x = function hello() {}; if (x) { - // 函数表达式 - function world() {} + // 函数表达式 + function world() {} } // 函数声明 function a() { - // 函数声明 - function b() {} - if (0) { - //函数表达式 - function c() {} - } + // 函数声明 + function b() {} + if (0) { + //函数表达式 + function c() {} + } } ``` @@ -371,7 +374,7 @@ function a() { 从 ECMAScript 6 开始,在[严格模式](/zh-CN/docs/Web/JavaScript/Reference/Strict_mode)下,块里的函数作用域为这个块。ECMAScript 6 之前不建议块级函数在严格模式下使用。 ```js -'use strict'; +"use strict"; function f() { return 1; @@ -396,9 +399,10 @@ f() === 1; // true ```js if (shouldDefineZero) { - function zero() { // DANGER: 兼容性风险 - console.log("This is zero."); - } + function zero() { + // DANGER: 兼容性风险 + console.log("This is zero."); + } } ``` @@ -411,9 +415,9 @@ ECMAScript 6 中,如果`shouldDefineZero`是 false,则永远不会定义 zer ```js var zero; if (0) { - zero = function() { - console.log("This is zero."); - }; + zero = function () { + console.log("This is zero."); + }; } ``` @@ -426,12 +430,12 @@ if (0) { ```js // 这个函数返回一个由 0 开头并填充的字符串 function padZeros(num, totalLen) { - var numStr = num.toString(); // 用字符串返回值进行初始化 - var numZeros = totalLen - numStr.length; // 计算 zeros 顺序 - for (var i = 1; i <= numZeros; i++) { - numStr = "0" + numStr; - } - return numStr; + var numStr = num.toString(); // 用字符串返回值进行初始化 + var numZeros = totalLen - numStr.length; // 计算 zeros 顺序 + for (var i = 1; i <= numZeros; i++) { + numStr = "0" + numStr; + } + return numStr; } ``` @@ -439,9 +443,9 @@ function padZeros(num, totalLen) { ```js var result; -result = padZeros(42,4); // returns "0042" -result = padZeros(42,2); // returns "42" -result = padZeros(5,4); // returns "0005" +result = padZeros(42, 4); // returns "0042" +result = padZeros(42, 2); // returns "42" +result = padZeros(5, 4); // returns "0005" ``` ### 检测函数是否存在 @@ -449,11 +453,11 @@ result = padZeros(5,4); // returns "0005" 你可以通过 **typeof** 操作符检测一个函数是否存在。在下面的例子中,用一个测试来演示检测 window 对象是否拥有一个 noFunc 函数的属性。如果存在,那就使用它;否则就采取其他的一些操作。 ```js -if ('function' === typeof window.noFunc) { - // use noFunc() - } else { - // do something else - } +if ("function" === typeof window.noFunc) { + // use noFunc() +} else { + // do something else +} ``` 注意在 if 语句中,使用了 noFunc 的引用——在函数名的后面没有括号“()”,所以实际函数并没有被调用。 diff --git a/files/zh-cn/web/javascript/reference/functions/method_definitions/index.md b/files/zh-cn/web/javascript/reference/functions/method_definitions/index.md index 2424e521968e01..71d2302d7a5975 100644 --- a/files/zh-cn/web/javascript/reference/functions/method_definitions/index.md +++ b/files/zh-cn/web/javascript/reference/functions/method_definitions/index.md @@ -37,12 +37,12 @@ var obj = { ```js var obj = { - foo: function() { + foo: function () { /* code */ }, - bar: function() { + bar: function () { /* code */ - } + }, }; ``` @@ -55,7 +55,7 @@ var obj = { }, bar() { /* code */ - } + }, }; ``` @@ -71,20 +71,18 @@ var obj = { ```js // 用有属性名的语法定义方法(ES6 之前): var obj2 = { - g: function*() { + g: function* () { var index = 0; - while(true) - yield index++; - } + while (true) yield index++; + }, }; // 同一个方法,简写语法: var obj2 = { - * g() { + *g() { var index = 0; - while(true) - yield index++; - } + while (true) yield index++; + }, }; var it = obj2.g(); @@ -101,14 +99,14 @@ console.log(it.next().value); // 1 var obj3 = { f: async function () { await some_promise; - } + }, }; // 同一个方法,简写语法: var obj3 = { async f() { await some_promise; - } + }, }; ``` @@ -122,16 +120,16 @@ var obj4 = { yield 1; yield 2; yield 3; - } + }, }; // The same object using shorthand syntax var obj4 = { - async* f() { - yield 1; - yield 2; - yield 3; - } + async *f() { + yield 1; + yield 2; + yield 3; + }, }; ``` @@ -141,14 +139,14 @@ var obj4 = { ```js example-bad var obj = { - method() {} + method() {}, }; -new obj.method; // TypeError: obj.method is not a constructor +new obj.method(); // TypeError: obj.method is not a constructor var obj = { - * g() {} + *g() {}, }; -new obj.g; // TypeError: obj.g is not a constructor (changed in ES2016) +new obj.g(); // TypeError: obj.g is not a constructor (changed in ES2016) ``` ## 示例 @@ -157,8 +155,10 @@ new obj.g; // TypeError: obj.g is not a constructor (changed in ES2016) ```js var obj = { - a : "foo", - b(){ return this.a; } + a: "foo", + b() { + return this.a; + }, }; console.log(obj.b()); // "foo" ``` @@ -169,9 +169,15 @@ console.log(obj.b()); // "foo" ```js var bar = { - foo0: function() { return 0; }, - foo1() { return 1; }, - ['foo' + 2]() { return 2; } + foo0: function () { + return 0; + }, + foo1() { + return 1; + }, + ["foo" + 2]() { + return 2; + }, }; console.log(bar.foo0()); // 0 diff --git a/files/zh-cn/web/javascript/reference/functions/rest_parameters/index.md b/files/zh-cn/web/javascript/reference/functions/rest_parameters/index.md index 81320d5a0029ad..3e721c5712f50a 100644 --- a/files/zh-cn/web/javascript/reference/functions/rest_parameters/index.md +++ b/files/zh-cn/web/javascript/reference/functions/rest_parameters/index.md @@ -68,9 +68,9 @@ function f(...[a, b, c]) { return a + b + c; } -f(1) // NaN (b and c are undefined) -f(1, 2, 3) // 6 -f(1, 2, 3, 4) // 6 (the fourth parameter is not destructured) +f(1); // NaN (b and c are undefined) +f(1, 2, 3); // 6 +f(1, 2, 3, 4); // 6 (the fourth parameter is not destructured) ``` ## 示例 @@ -82,7 +82,7 @@ function fun1(...theArgs) { alert(theArgs.length); } -fun1(); // 弹出 "0", 因为 theArgs 没有元素 +fun1(); // 弹出 "0", 因为 theArgs 没有元素 fun1(5); // 弹出 "1", 因为 theArgs 只有一个元素 fun1(5, 6, 7); // 弹出 "3", 因为 theArgs 有三个元素 ``` @@ -97,7 +97,7 @@ function multiply(multiplier, ...theArgs) { } var arr = multiply(2, 1, 2, 3); -console.log(arr); // [2, 4, 6] +console.log(arr); // [2, 4, 6] ``` 下例演示了你可以在剩余参数上使用任意的数组方法,而`arguments`对象不可以: @@ -108,14 +108,14 @@ function sortRestArgs(...theArgs) { return sortedArgs; } -alert(sortRestArgs(5,3,7,1)); // 弹出 1,3,5,7 +alert(sortRestArgs(5, 3, 7, 1)); // 弹出 1,3,5,7 function sortArguments() { var sortedArgs = arguments.sort(); return sortedArgs; // 不会执行到这里 } -alert(sortArguments(5,3,7,1)); // 抛出 TypeError 异常:arguments.sort is not a function +alert(sortArguments(5, 3, 7, 1)); // 抛出 TypeError 异常:arguments.sort is not a function ``` 为了在`arguments`对象上使用`Array`方法,它必须首先被转换为一个真正的数组。 diff --git a/files/zh-cn/web/javascript/reference/functions/set/index.md b/files/zh-cn/web/javascript/reference/functions/set/index.md index fb9ab9af106c1f..9a1192178bd958 100644 --- a/files/zh-cn/web/javascript/reference/functions/set/index.md +++ b/files/zh-cn/web/javascript/reference/functions/set/index.md @@ -47,13 +47,13 @@ const language = { set current(name) { this.log.push(name); }, - log: [] -} + log: [], +}; -language.current = 'EN'; +language.current = "EN"; console.log(language.log); // ['EN'] -language.current = 'FA'; +language.current = "FA"; console.log(language.log); // ['EN', 'FA'] ``` @@ -72,12 +72,16 @@ delete language.current; 我们可以随时使用 {{jsxref("Object.defineProperty()")}} 给一个已经存在的对象添加一个 setter。 ```js -const o = { a:0 }; +const o = { a: 0 }; -Object.defineProperty(o, "b", { set: function (x) { this.a = x / 2; } }); +Object.defineProperty(o, "b", { + set: function (x) { + this.a = x / 2; + }, +}); o.b = 10; // Runs the setter, which assigns 10 / 2 (5) to the 'a' property -console.log(o.a) // 5 +console.log(o.a); // 5 ``` ### 使用计算属性名 @@ -87,11 +91,13 @@ const expr = "foo"; const obj = { baz: "bar", - set [expr](v) { this.baz = v; } + set [expr](v) { + this.baz = v; + }, }; console.log(obj.baz); // "bar" -obj.foo = "baz"; // run the setter +obj.foo = "baz"; // run the setter console.log(obj.baz); // "baz" ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/aggregateerror/index.md b/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/aggregateerror/index.md index 069eef13994a75..71e7e3f4f4b2d8 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/aggregateerror/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/aggregateerror/index.md @@ -38,14 +38,12 @@ AggregateError(errors, message, options) ```js try { - throw new AggregateError([ - new Error("some error"), - ], 'Hello'); + throw new AggregateError([new Error("some error")], "Hello"); } catch (e) { console.log(e instanceof AggregateError); // true - console.log(e.message); // "Hello" - console.log(e.name); // "AggregateError" - console.log(e.errors); // [ Error: "some error" ] + console.log(e.message); // "Hello" + console.log(e.name); // "AggregateError" + console.log(e.errors); // [ Error: "some error" ] } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/index.md b/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/index.md index 47310478f037a4..c85d242f874b48 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/aggregateerror/index.md @@ -39,13 +39,11 @@ _从父类 {{jsxref("Error")}} 中继承实例方法。_ ### 捕获一个 AggregateError ```js -Promise.any([ - Promise.reject(new Error("some error")), -]).catch((e) => { +Promise.any([Promise.reject(new Error("some error"))]).catch((e) => { console.log(e instanceof AggregateError); // true - console.log(e.message); // "All Promises rejected" - console.log(e.name); // "AggregateError" - console.log(e.errors); // [ Error: "some error" ] + console.log(e.message); // "All Promises rejected" + console.log(e.name); // "AggregateError" + console.log(e.errors); // [ Error: "some error" ] }); ``` @@ -53,14 +51,12 @@ Promise.any([ ```js try { - throw new AggregateError([ - new Error("some error"), - ], 'Hello'); + throw new AggregateError([new Error("some error")], "Hello"); } catch (e) { console.log(e instanceof AggregateError); // true - console.log(e.message); // "Hello" - console.log(e.name); // "AggregateError" - console.log(e.errors); // [ Error: "some error" ] + console.log(e.message); // "Hello" + console.log(e.name); // "AggregateError" + console.log(e.errors); // [ Error: "some error" ] } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/@@unscopables/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/@@unscopables/index.md index 1d032d4aa3f3f5..29452edd874938 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/@@unscopables/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/@@unscopables/index.md @@ -45,7 +45,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Array/@@unscopables ```js var keys = []; -with(Array.prototype) { +with (Array.prototype) { keys.push("something"); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/at/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/at/index.md index 983c431e29f5de..7ef29588a73154 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/at/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/at/index.md @@ -66,7 +66,7 @@ console.log(item2); // 输出:'orange' const colors = ["red", "green", "blue"]; // 使用长度属性 -const lengthWay = colors[colors.length-2]; +const lengthWay = colors[colors.length - 2]; console.log(lengthWay); // 输出:'green' // 使用 slice() 方法。注意会返回一个数组 diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/every/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/every/index.md index b3cfb8f425639d..df47aef1c6300a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/every/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/every/index.md @@ -61,7 +61,7 @@ every(callbackFn, thisArg) function isBigEnough(element, index, array) { return element >= 10; } -[12, 5, 8, 130, 44].every(isBigEnough); // false +[12, 5, 8, 130, 44].every(isBigEnough); // false [12, 54, 18, 130, 44].every(isBigEnough); // true ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/filter/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/filter/index.md index ebee2461cb5686..ca23f7477d4d36 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/filter/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/filter/index.md @@ -131,7 +131,7 @@ const fruits = ["apple", "banana", "grapes", "mango", "orange"]; * 根据搜索条件(查询)筛选数组项 */ function filterItems(arr, query) { - return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase())); + return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase())); } console.log(filterItems(fruits, "ap")); // ['apple', 'grapes'] @@ -184,7 +184,7 @@ words = ["spray", "limit", "exuberant", "destruction", "elite", "present"]; const appendedWords = words.filter((word, index, arr) => { arr.push("new"); return word.length < 6; -}) +}); console.log(appendedWords); // 只有三个符合条件,即使 `words` 本身现在有更多字符长度小于 6 的单词 @@ -195,7 +195,7 @@ words = ["spray", "limit", "exuberant", "destruction", "elite", "present"]; const deleteWords = words.filter((word, index, arr) => { arr.pop(); return word.length < 6; -}) +}); console.log(deleteWords); // 注意我们没有得到 'elite',因为它在过滤器访问到它之前就已经从 'words' 弹出了 diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/find/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/find/index.md index 4df4b83e1194ad..61ab134da5d34a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/find/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/find/index.md @@ -44,7 +44,7 @@ find(callbackFn, thisArg) `callbackFn` 被调用来处理数组的*每一个*索引,而不仅仅是那些有值的索引。在[稀疏数组](/zh-CN/docs/Web/JavaScript/Guide/Indexed_collections#稀疏数组)中,未赋值的空槽与 `undefined` 表现相同。 -`find()` 不会改变被调用的数组,但是提供给 `callbackFn` 的函数可能会改变它。但需要注意的是,在第一次调用 `callbackFn` *之前*,数组的长度会被保存。因此: +`find()` 不会改变被调用的数组,但是提供给 `callbackFn` 的函数可能会改变它。但需要注意的是,在第一次调用 `callbackFn` _之前_,数组的长度会被保存。因此: - 当调用 `find()` 时,`callbackFn` 不会访问超出数组初始长度的任何元素。 - 对已经访问过的索引的更改不会导致再次在这些元素上调用 `callbackFn`。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/findindex/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/findindex/index.md index 8026fca99004c5..d76d9e3d621f24 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/findindex/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/findindex/index.md @@ -41,7 +41,7 @@ findIndex(callbackFn, thisArg) `callbackFn` 被调用来处理数组的*每一个*索引,而不仅仅是那些有值的索引。在[稀疏数组](/zh-CN/docs/Web/JavaScript/Guide/Indexed_collections#稀疏数组)中,未赋值的空槽与 `undefined` 表现相同。 -`findIndex()` 不会改变被调用的数组,但是提供给 `callbackFn` 的函数可能会改变它。但需要注意的是,在第一次调用 `callbackFn` *之前*,数组的长度会被保存。因此: +`findIndex()` 不会改变被调用的数组,但是提供给 `callbackFn` 的函数可能会改变它。但需要注意的是,在第一次调用 `callbackFn` _之前_,数组的长度会被保存。因此: - 当调用 `findIndex()` 时,`callbackFn` 不会访问超出数组初始长度的任何元素。 - 对已经访问过的索引的更改不会导致再次在这些元素上调用 `callbackFn`。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/findlast/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/findlast/index.md index 5aea130403b3fd..11f7a465f60d2b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/findlast/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/findlast/index.md @@ -53,7 +53,7 @@ findLast(callbackFn, thisArg) - 给已访问过的索引重新赋值将不会被 `callbackFn` 重新访问。 - 如果 `callbackFn` 更改了数组中现有的、尚未访问的元素,则其传递给 `callbackFn` 的值将是 `findLast()` 访问该元素索引时的值。[已删除](/zh-CN/docs/Web/JavaScript/Reference/Operators/delete)的元素会被当做 `undefined` 来访问。 ->**警告:** 上一段描述的并发修改的情况经常导致难以理解的代码,通常应该避免(特殊情况除外)。 +> **警告:** 上一段描述的并发修改的情况经常导致难以理解的代码,通常应该避免(特殊情况除外)。 `findLast()` 方法是[通用的](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array#通用数组方法)。它只期望 `this` 值具有 `length` 属性和整数键的属性。 @@ -92,9 +92,9 @@ const inventory = [ { name: "cherries", quantity: 5 }, ]; -const result = inventory.findLast( ({ quantity }) => quantity < 2 ); +const result = inventory.findLast(({ quantity }) => quantity < 2); -console.log(result) +console.log(result); // { name: "fish", quantity: 1 } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/findlastindex/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/findlastindex/index.md index 861c588693cd83..0d0a42909b5b75 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/findlastindex/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/findlastindex/index.md @@ -29,6 +29,7 @@ findLastIndex(callbackFn, thisArg) - : 当前正在处理的元素的索引。 - `array` - : 调用 `findLastIndex()` 的数组本身。 + - `thisArg` {{optional_inline}} - : 执行 `callbackFn` 时,用作 `this` 的值。参见[迭代方法](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array#迭代方法)。 @@ -48,7 +49,7 @@ findLastIndex(callbackFn, thisArg) - 对已访问索引的更改不会导致对它们再次调用 `callbackFn` 函数。 - 如果 `callbackFn` 更改了数组中现有的、尚未访问的元素,它传递给`callbackFn` 的值将是该元素被访问时的值。[已删除](/zh-CN/docs/Web/JavaScript/Reference/Operators/delete)元素被当作 `undefined` 来访问。 ->**警告:** 上一段描述的并发修改的情况经常导致难以理解的代码,通常应该避免(特殊情况除外)。 +> **警告:** 上一段描述的并发修改的情况经常导致难以理解的代码,通常应该避免(特殊情况除外)。 `findLastIndex()` 方法是[通用的](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array#通用数组方法)。它只期望 `this` 值具有 `length` 属性和整型键属性。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/foreach/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/foreach/index.md index 3408ee53b4529e..5baf25b09759f0 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/foreach/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/foreach/index.md @@ -76,7 +76,7 @@ console.log(sum); ### 在稀疏数组上使用 forEach() -```js +```js-nolint const arraySparse = [1, 3, /* empty */, 7]; let numCallbackRuns = 0; @@ -142,7 +142,7 @@ class Counter { this.count = 0; } add(array) { - // 只有函数表达式才有自己的 this 绑定 + // 只有函数表达式才有自己的 this 绑定 array.forEach(function countEntry(entry) { this.sum += entry; ++this.count; @@ -214,7 +214,7 @@ const flatten = (arr) => { } }); return result; -} +}; // 用例 const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]; diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/index.md index 3594af816e7292..e2331c9495c193 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/index.md @@ -31,7 +31,7 @@ JavaScript 语法要求使用[方括号表示法](/zh-CN/docs/Web/JavaScript/Gui JavaScript 引擎通过隐式的 `toString`,将 `years[2]` 中的 `2` 强制转换为字符串。因此,`'2'` 和 `'02'` 将指向 `years` 对象上的两个不同的槽位,下面的例子可能是 `true`: ```js -console.log(years['2'] !== years['02']); +console.log(years["2"] !== years["02"]); ``` 只有 `years['2']` 是一个实际的数组索引。`years['02']` 是一个在数组迭代中不会被访问的任意字符串属性。 @@ -123,7 +123,7 @@ console.log(fruits.length); // 2 ### 复制方法和修改方法 -有些方法不会修改调用该方法的现有数组,而是返回一个新的数组。它们通过首先构造一个新数组,然后填充元素来实现。复制始终是[*浅层次的*](/zh-CN/docs/Glossary/Shallow_copy)——该方法从不复制一开始创建的数组之外的任何内容。原始数组的元素将按以下方式复制到新数组中: +有些方法不会修改调用该方法的现有数组,而是返回一个新的数组。它们通过首先构造一个新数组,然后填充元素来实现。复制始终是[_浅层次的_](/zh-CN/docs/Glossary/Shallow_copy)——该方法从不复制一开始创建的数组之外的任何内容。原始数组的元素将按以下方式复制到新数组中: - 对象:对象引用被复制到新数组中。原数组和新数组都引用同一个对象。也就是说,如果一个被引用的对象被修改,新数组和原数组都可以看到更改。 - 基本类型,如字符串、数字和布尔值(不是 {{jsxref("Global_Objects/String", "String")}}、{{jsxref("Global_Objects/Number", "Number")}} 和 {{jsxref("Global_Objects/Boolean", "Boolean")}} 对象):它们的值被复制到新数组中。 @@ -151,16 +151,16 @@ console.log(fruits.length); // 2 下表列出了会修改原始数组的方法,以及相应的非修改方法: -| 修改方法 | 相应的非修改方法 | -| ---------------------------------------------- | ----------------------------------------------------- | +| 修改方法 | 相应的非修改方法 | +| ---------------------------------------------- | -------------------------------------------------------- | | {{jsxref("Array/copyWithin", "copyWithin()")}} | 没有相应的非修改方法 | | {{jsxref("Array/fill", "fill()")}} | 没有相应的非修改方法 | -| {{jsxref("Array/pop", "pop()")}} | {{jsxref("Array/slice", "slice(0, -1)")}} | -| {{jsxref("Array/push", "push(v1, v2)")}} | {{jsxref("Array/concat", "concat([v1, v2])")}} | -| {{jsxref("Array/reverse", "reverse()")}} | {{jsxref("Array/toReversed", "toReversed()")}} | -| {{jsxref("Array/shift", "shift()")}} | {{jsxref("Array/slice", "slice(1)")}} | -| {{jsxref("Array/sort", "sort()")}} | {{jsxref("Array/toSorted", "toSorted()")}} | -| {{jsxref("Array/splice", "splice()")}} | {{jsxref("Array/toSpliced", "toSpliced()")}} | +| {{jsxref("Array/pop", "pop()")}} | {{jsxref("Array/slice", "slice(0, -1)")}} | +| {{jsxref("Array/push", "push(v1, v2)")}} | {{jsxref("Array/concat", "concat([v1, v2])")}} | +| {{jsxref("Array/reverse", "reverse()")}} | {{jsxref("Array/toReversed", "toReversed()")}} | +| {{jsxref("Array/shift", "shift()")}} | {{jsxref("Array/slice", "slice(1)")}} | +| {{jsxref("Array/sort", "sort()")}} | {{jsxref("Array/toSorted", "toSorted()")}} | +| {{jsxref("Array/splice", "splice()")}} | {{jsxref("Array/toSpliced", "toSpliced()")}} | | {{jsxref("Array/unshift", "unshift(v1, v2)")}} | {{jsxref("Array/toSpliced", "toSpliced(0, 0, v1, v2)")}} | 将改变原数组的方法转换为非修改方法的一种简单方式是使用[展开语法](/zh-CN/docs/Web/JavaScript/Reference/Operators/Spread_syntax)或 {{jsxref("Array/slice", "slice()")}} 先创建一个副本: @@ -251,7 +251,7 @@ console.log(a.length); // 0 #### 类数组对象 -术语[*类数组对象*](/zh-CN/docs/Web/JavaScript/Guide/Indexed_collections#使用类数组对象)指的是在上面描述的 `length` 转换过程中不抛出的任何对象。在实践中,这样的对象应该实际具有 `length` 属性,并且索引元素的范围在 `0` 到 `length - 1` 之间。(如果它没有所有的索引,它将在功能上等同于[稀疏数组](#数组方法和空槽)。) +术语[_类数组对象_](/zh-CN/docs/Web/JavaScript/Guide/Indexed_collections#使用类数组对象)指的是在上面描述的 `length` 转换过程中不抛出的任何对象。在实践中,这样的对象应该实际具有 `length` 属性,并且索引元素的范围在 `0` 到 `length - 1` 之间。(如果它没有所有的索引,它将在功能上等同于[稀疏数组](#数组方法和空槽)。) 许多 DOM 对象都是类数组对象——例如 [`NodeList`](/zh-CN/docs/Web/API/NodeList) 和 [`HTMLCollection`](/zh-CN/docs/Web/API/HTMLCollection)。[`arguments`](/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments) 对象也是类数组对象。你可以在它们上调用数组方法,即使它们本身没有这些方法。 @@ -307,7 +307,7 @@ f("a", "b"); // 'a+b' - {{jsxref("Array.prototype.copyWithin()")}} - : 在数组内复制数组元素序列。 - {{jsxref("Array.prototype.entries()")}} - - : 返回一个新的[*数组迭代器*](/zh-CN/docs/Web/JavaScript/Guide/Iterators_and_generators)对象,其中包含数组中每个索引的键/值对。 + - : 返回一个新的[_数组迭代器_](/zh-CN/docs/Web/JavaScript/Guide/Iterators_and_generators)对象,其中包含数组中每个索引的键/值对。 - {{jsxref("Array.prototype.every()")}} - : 如果调用数组中的每个元素都满足测试函数,则返回 `true`。 - {{jsxref("Array.prototype.fill()")}} @@ -339,7 +339,7 @@ f("a", "b"); // 'a+b' - {{jsxref("Array.prototype.join()")}} - : 将数组的所有元素连接为字符串。 - {{jsxref("Array.prototype.keys()")}} - - : 返回一个新的[*数组迭代器*](/zh-CN/docs/Web/JavaScript/Guide/Iterators_and_generators),其中包含调用数组中每个索引的键。 + - : 返回一个新的[_数组迭代器_](/zh-CN/docs/Web/JavaScript/Guide/Iterators_and_generators),其中包含调用数组中每个索引的键。 - {{jsxref("Array.prototype.lastIndexOf()")}} - : 返回在调用数组中可以找到给定元素的最后一个(最大)索引,如果找不到则返回 `-1`。 - {{jsxref("Array.prototype.map()")}} @@ -377,7 +377,7 @@ f("a", "b"); // 'a+b' - {{jsxref("Array.prototype.unshift()")}} - : 在数组的前面添加一个或多个元素,并返回数组新的 `length`。 - {{jsxref("Array.prototype.values()")}} - - : 返回一个新的[*数组迭代器*](/zh-CN/docs/Web/JavaScript/Guide/Iterators_and_generators)对象,该对象包含数组中每个索引的值。 + - : 返回一个新的[_数组迭代器_](/zh-CN/docs/Web/JavaScript/Guide/Iterators_and_generators)对象,该对象包含数组中每个索引的值。 - {{jsxref("Array.prototype.with()")}} - : 返回一个新数组,其中给定索引处的元素替换为给定值,而不改变原始数组。 - [`Array.prototype[@@iterator]()`](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/@@iterator) @@ -447,7 +447,7 @@ fruits[99]; // undefined ```js const fruits = ["Apple", "Banana"]; -console.log(fruits.indexOf('Banana')); +console.log(fruits.indexOf("Banana")); // 1 ``` @@ -603,7 +603,7 @@ console.log(removedItems); const fruits = ["Apple", "Banana", "Strawberry"]; const start = -2; const deleteCount = 2; -const removedItems = fruits.splice(start, deleteCount, 'Mango', 'Cherry'); +const removedItems = fruits.splice(start, deleteCount, "Mango", "Cherry"); console.log(fruits); // ["Apple", "Mango", "Cherry"] console.log(removedItems); @@ -615,7 +615,7 @@ console.log(removedItems); 下面的例子使用 [`for...of`](/zh-CN/docs/Web/JavaScript/Reference/Statements/for...of) 循环遍历 `fruits` 数组,将每一个元素打印到控制台。 ```js -const fruits = ['Apple', 'Mango', 'Cherry']; +const fruits = ["Apple", "Mango", "Cherry"]; for (const fruit of fruits) { console.log(fruit); } @@ -694,7 +694,7 @@ const fruitsDeepCopy = JSON.parse(JSON.stringify(fruits)); const fruits = ["Strawberry", "Mango"]; const fruitsAlias = fruits; // 'fruits' 和 'fruitsAlias' 是同一个对象,严格相等。 -fruits === fruitsAlias // true +fruits === fruitsAlias; // true // 对 'fruits' 数组的任何更改也会更改 'fruitsAlias'。 fruits.unshift("Apple", "Banana"); console.log(fruits); @@ -711,11 +711,11 @@ console.log(fruitsAlias); ```js const inventory = [ - { name: 'asparagus', type: 'vegetables' }, - { name: 'bananas', type: 'fruit' }, - { name: 'goat', type: 'meat' }, - { name: 'cherries', type: 'fruit' }, - { name: 'fish', type: 'meat' }, + { name: "asparagus", type: "vegetables" }, + { name: "bananas", type: "fruit" }, + { name: "goat", type: "meat" }, + { name: "cherries", type: "fruit" }, + { name: "fish", type: "meat" }, ]; ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/isarray/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/isarray/index.md index df562cbcd5b148..b087049920efde 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/isarray/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/isarray/index.md @@ -71,7 +71,7 @@ const xArray = window.frames[window.frames.length - 1].Array; const arr = new xArray(1, 2, 3); // [1, 2, 3] // 正确检查 Array -Array.isArray(arr); // true +Array.isArray(arr); // true // arr 的原型是 xArray.prototype,它是一个不同于 Array.prototype 的对象 arr instanceof Array; // false ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/join/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/join/index.md index 53ba3f0f68f771..5ea62811ee4bd7 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/join/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/join/index.md @@ -55,7 +55,7 @@ a.join(""); // 'WindWaterFire' ```js console.log([1, , 3].join()); // '1,,3' -console.log([1, undefined, 3].join()); // '1,,3' +console.log([1, undefined, 3].join()); // '1,,3' ``` ### 在非数组对象上调用 join() diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/keys/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/keys/index.md index 9bb1b2fb8f5bb5..158206013529af 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/keys/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/keys/index.md @@ -5,7 +5,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Array/keys {{JSRef}} -**`keys()`** 方法返回一个新的[*数组迭代器*](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Iterator)对象,其中包含数组中每个索引的键。 +**`keys()`** 方法返回一个新的[_数组迭代器_](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Iterator)对象,其中包含数组中每个索引的键。 {{EmbedInteractiveExample("pages/js/array-keys.html")}} diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/length/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/length/index.md index 6b29298f196805..c9579f781bd8e2 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/length/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/length/index.md @@ -32,7 +32,7 @@ console.log(listB.length); listB.length = 2 ** 32; // 4294967296 // RangeError: Invalid array length -const listC = new Array(-100) // 负数是不允许的 +const listC = new Array(-100); // 负数是不允许的 // RangeError: Invalid array length ``` @@ -53,7 +53,7 @@ arr.length = 5; // 将数组长度设置为 5,而当前为 2。 console.log(arr); // [ 1, 2, <3 empty items> ] -arr.forEach(element => console.log(element)); +arr.forEach((element) => console.log(element)); // 1 // 2 ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/map/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/map/index.md index fc8a831665c8bf..19e4eee48830c7 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/map/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/map/index.md @@ -76,7 +76,7 @@ const kvArray = [ { key: 3, value: 30 }, ]; -const reformattedArray = kvArray.map(({ key, value}) => ({ [key]: value })); +const reformattedArray = kvArray.map(({ key, value }) => ({ [key]: value })); console.log(reformattedArray); // [{ 1: 10 }, { 2: 20 }, { 3: 30 }] console.log(kvArray); diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/of/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/of/index.md index 36911f791da2c0..b356f71ff43cdb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/of/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/of/index.md @@ -36,7 +36,7 @@ Array.of(7); // [7] Array(7); // 由 7 个空槽组成的数组 Array.of(1, 2, 3); // [1, 2, 3] -Array(1, 2, 3); // [1, 2, 3] +Array(1, 2, 3); // [1, 2, 3] ``` `Array.of()` 方法是一个通用的工厂方法。例如,如果 `Array` 的子类继承了 `of()` 方法,继承的 `of()` 方法将返回子类的新实例而不是 `Array` 实例。事实上,`this` 值可以是任何接受单个参数表示新数组长度的构造函数,并且构造函数将与传递给 `of()` 的参数数量一起被调用。当所有元素都被分配时,最终的 `length` 将再次设置。如果 `this` 值不是构造函数,则改用普通的 `Array` 构造函数。 @@ -46,8 +46,8 @@ Array(1, 2, 3); // [1, 2, 3] ### 使用 Array.of() ```js -Array.of(1); // [1] -Array.of(1, 2, 3); // [1, 2, 3] +Array.of(1); // [1] +Array.of(1, 2, 3); // [1, 2, 3] Array.of(undefined); // [undefined] ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/reduceright/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/reduceright/index.md index 6f8a0f7cda251c..8152693174ac65 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/reduceright/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/reduceright/index.md @@ -81,12 +81,12 @@ arr.reduceRight((accumulator, currentValue, index, array) => { 一共会调用四次回调函数,每次调用的参数及返回值如下: -| | `accumulator` | `currentValue` | `index` | 返回值 | -| -------- | ------------- | -------------- | ------- | ----- | -| 第一次调用 | `4` | `3` | `3` | `7` | -| 第二次调用 | `7` | `2` | `2` | `9` | -| 第三次调用 | `9` | `1` | `1` | `10` | -| 第四次调用 | `10` | `0` | `0` | `10` | +| | `accumulator` | `currentValue` | `index` | 返回值 | +| ---------- | ------------- | -------------- | ------- | ------ | +| 第一次调用 | `4` | `3` | `3` | `7` | +| 第二次调用 | `7` | `2` | `2` | `9` | +| 第三次调用 | `9` | `1` | `1` | `10` | +| 第四次调用 | `10` | `0` | `0` | `10` | `array` 参数在整个过程中始终不变,始终为 `[0, 1, 2, 3, 4]`。`reduceRight` 返回的值将是最后一次回调函数调用的返回值(`10`)。 @@ -101,13 +101,13 @@ arr.reduceRight((accumulator, currentValue, index, array) => { ); ``` -| | `accumulator` | `currentValue` | `index` | 返回值 | -| -------- | ------------- | -------------- | ------- | ----- | -| 第一次调用 | `10` | `4` | `4` | `14` | -| 第二次调用 | `14` | `3` | `3` | `17` | -| 第三次调用 | `17` | `2` | `2` | `19` | -| 第四次调用 | `19` | `1` | `1` | `20` | -| 第五次调用 | `20` | `0` | `0` | `20` | +| | `accumulator` | `currentValue` | `index` | 返回值 | +| ---------- | ------------- | -------------- | ------- | ------ | +| 第一次调用 | `10` | `4` | `4` | `14` | +| 第二次调用 | `14` | `3` | `3` | `17` | +| 第三次调用 | `17` | `2` | `2` | `19` | +| 第四次调用 | `19` | `1` | `1` | `20` | +| 第五次调用 | `20` | `0` | `0` | `20` | 这次,`reduceRight` 返回值为 `20`。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/shift/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/shift/index.md index 8280e78372c0f2..90df9cd3d0b2eb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/shift/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/shift/index.md @@ -43,10 +43,10 @@ console.log("调用 shift 之前:", myFish); const shifted = myFish.shift(); -console.log('调用 shift 之后:', myFish); +console.log("调用 shift 之后:", myFish); // 调用 shift 之后: ['clown', 'mandarin', 'surgeon'] -console.log('被删除的元素:' + shifted); +console.log("被删除的元素:" + shifted); // "被删除的元素:angel" ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/sort/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/sort/index.md index 0b23ec15742c2b..1b87760978ecd3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/sort/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/sort/index.md @@ -47,11 +47,11 @@ sort(compareFn) 如果提供了 `compareFn`,所有非 `undefined` 的数组元素都会按照比较函数的返回值进行排序(所有的 `undefined` 元素都会被排序到数组的末尾,并且不调用 `compareFn`)。 -| `compareFn(a, b)` 返回值 | 排序顺序 | -| ----------------------- | ------------------------ | -| > 0 | `a` 在 `b` 后,如 `[b, a]` | -| < 0 | `a` 在 `b` 前,如 `[a, b]` | -| === 0 | 保持 `a` 和 `b` 原来的顺序 | +| `compareFn(a, b)` 返回值 | 排序顺序 | +| ------------------------ | -------------------------- | +| > 0 | `a` 在 `b` 后,如 `[b, a]` | +| < 0 | `a` 在 `b` 前,如 `[a, b]` | +| === 0 | 保持 `a` 和 `b` 原来的顺序 | 所以,比较函数形式如下: @@ -160,7 +160,7 @@ items.sort((a, b) => { 当排序非 ASCII 字符的字符串(如包含类似 e、é、è、a、ä 等字符的字符串)。一些非英语语言的字符串需要使用 {{jsxref("String.localeCompare")}}。这个函数可以将函数排序到正确的顺序。 ```js -var items = ['réservé', 'premier', 'cliché', 'communiqué', 'café', 'adieu']; +var items = ["réservé", "premier", "cliché", "communiqué", "café", "adieu"]; items.sort(function (a, b) { return a.localeCompare(b); }); @@ -227,10 +227,10 @@ console.log(numbers[0]); // 3 ```js const students = [ - { name: "Alex", grade: 15 }, + { name: "Alex", grade: 15 }, { name: "Devlin", grade: 15 }, - { name: "Eagle", grade: 13 }, - { name: "Sam", grade: 14 }, + { name: "Eagle", grade: 13 }, + { name: "Sam", grade: 14 }, ]; ``` @@ -244,9 +244,9 @@ students.sort((firstItem, secondItem) => firstItem.grade - secondItem.grade); ```js [ - { name: "Eagle", grade: 13 }, - { name: "Sam", grade: 14 }, - { name: "Alex", grade: 15 }, // grade 相同时维持原先的顺序(稳定排序) + { name: "Eagle", grade: 13 }, + { name: "Sam", grade: 14 }, + { name: "Alex", grade: 15 }, // grade 相同时维持原先的顺序(稳定排序) { name: "Devlin", grade: 15 }, // grade 相同时维持原先的顺序(稳定排序) ]; ``` @@ -257,10 +257,10 @@ EcmaScript 第 10 版(EcmaScript 2019)以前没有要求稳定性,意味 ```js [ - { name: "Eagle", grade: 13 }, - { name: "Sam", grade: 14 }, + { name: "Eagle", grade: 13 }, + { name: "Sam", grade: 14 }, { name: "Devlin", grade: 15 }, // 没有维持原先的顺序 - { name: "Alex", grade: 15 }, // 没有维持原先的顺序 + { name: "Alex", grade: 15 }, // 没有维持原先的顺序 ]; ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/tospliced/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/tospliced/index.md index d185f94ce05214..89d7e4b9ec0fce 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/tospliced/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/tospliced/index.md @@ -19,6 +19,7 @@ toSpliced(start, deleteCount, item1, item2, itemN) ### 参数 - `start` + - : 从 0 开始计算的索引,表示要开始改变数组的位置,它会被[转换为整数](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Number#整数转换)。 - 如果 `start < 0`,则从数组末尾开始计数,使用 `start + array.length`。 - 如果 `start < -array.length` 或者省略了 `start`,则使用 `0`。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/array/values/index.md b/files/zh-cn/web/javascript/reference/global_objects/array/values/index.md index 43999cdba57992..2786d7354033ad 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/array/values/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/array/values/index.md @@ -5,7 +5,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Array/values {{JSRef}} -**`values()`** 方法返回一个新的[*数组迭代器*](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Iterator)对象,该对象迭代数组中每个元素的值。 +**`values()`** 方法返回一个新的[_数组迭代器_](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Iterator)对象,该对象迭代数组中每个元素的值。 {{EmbedInteractiveExample("pages/js/array-values.html")}} diff --git a/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/@@species/index.md b/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/@@species/index.md index 3518d1337dfb2e..e1d6b3500e89e8 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/@@species/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/@@species/index.md @@ -30,7 +30,9 @@ ArrayBuffer[Symbol.species]; // function ArrayBuffer() ```js class MyArrayBuffer extends ArrayBuffer { // Overwrite MyArrayBuffer species to the parent ArrayBuffer constructor - static get [Symbol.species]() { return ArrayBuffer; } + static get [Symbol.species]() { + return ArrayBuffer; + } } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/isview/index.md b/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/isview/index.md index ba9f0a31145049..4a5f426575d2da 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/isview/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/arraybuffer/isview/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView ## 语法 -```js +```js-nolint ArrayBuffer.isView(value) ``` @@ -30,15 +30,15 @@ ArrayBuffer.isView(value) ## 示例 ```js -ArrayBuffer.isView(); // false -ArrayBuffer.isView([]); // false -ArrayBuffer.isView({}); // false -ArrayBuffer.isView(null); // false -ArrayBuffer.isView(undefined); // false +ArrayBuffer.isView(); // false +ArrayBuffer.isView([]); // false +ArrayBuffer.isView({}); // false +ArrayBuffer.isView(null); // false +ArrayBuffer.isView(undefined); // false ArrayBuffer.isView(new ArrayBuffer(10)); // false -ArrayBuffer.isView(new Uint8Array()); // true -ArrayBuffer.isView(new Float32Array()); // true +ArrayBuffer.isView(new Uint8Array()); // true +ArrayBuffer.isView(new Float32Array()); // true ArrayBuffer.isView(new Int8Array(10).subarray(0, 3)); // true var buffer = new ArrayBuffer(2); diff --git a/files/zh-cn/web/javascript/reference/global_objects/asyncgenerator/index.md b/files/zh-cn/web/javascript/reference/global_objects/asyncgenerator/index.md index 88ee2d2f7ca228..04644d1065b830 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/asyncgenerator/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/asyncgenerator/index.md @@ -22,12 +22,9 @@ async function* createAsyncGenerator() { yield await Promise.resolve(3); } const asyncGen = createAsyncGenerator(); -asyncGen.next() - .then((res) => console.log(res.value)); // 1 -asyncGen.next() - .then((res) => console.log(res.value)); // 2 -asyncGen.next() - .then((res) => console.log(res.value)); // 3 +asyncGen.next().then((res) => console.log(res.value)); // 1 +asyncGen.next().then((res) => console.log(res.value)); // 2 +asyncGen.next().then((res) => console.log(res.value)); // 3 ``` ## 实例属性 @@ -74,17 +71,16 @@ async function* generate() { yield delayedValue(250, 4); yield delayedValue(125, 5); yield delayedValue(50, 6); - console.log('All done!'); + console.log("All done!"); } async function main() { for await (const value of generate()) { - console.log('value', value); + console.log("value", value); } } -main() - .catch((e) => console.error(e)); +main().catch((e) => console.error(e)); ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/atomics/and/index.md b/files/zh-cn/web/javascript/reference/global_objects/atomics/and/index.md index fad68c19826ec6..db9c87fb7d9b2d 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/atomics/and/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/atomics/and/index.md @@ -63,7 +63,7 @@ var ta = new Uint8Array(sab); ta[0] = 5; Atomics.and(ta, 0, 1); // returns 0, the old value -Atomics.load(ta, 0); // 1 +Atomics.load(ta, 0); // 1 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/atomics/or/index.md b/files/zh-cn/web/javascript/reference/global_objects/atomics/or/index.md index 950ca10ea5f902..35a19bc9c37910 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/atomics/or/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/atomics/or/index.md @@ -63,7 +63,7 @@ var ta = new Uint8Array(sab); ta[0] = 2; Atomics.or(ta, 0, 1); // returns 2, the old value -Atomics.load(ta, 0); // 3 +Atomics.load(ta, 0); // 3 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/atomics/xor/index.md b/files/zh-cn/web/javascript/reference/global_objects/atomics/xor/index.md index a70c71282a247a..6603eff49c8e0e 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/atomics/xor/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/atomics/xor/index.md @@ -61,7 +61,7 @@ const ta = new Uint8Array(sab); ta[0] = 5; Atomics.xor(ta, 0, 1); // returns 5, the old value -Atomics.load(ta, 0); // 4 +Atomics.load(ta, 0); // 4 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/bigint/index.md b/files/zh-cn/web/javascript/reference/global_objects/bigint/index.md index 7678a577b3d84c..844968967eebb3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/bigint/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/bigint/index.md @@ -23,7 +23,9 @@ const hugeString = BigInt("9007199254740991"); const hugeHex = BigInt("0x1fffffffffffff"); // ↪ 9007199254740991n -const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111"); +const hugeBin = BigInt( + "0b11111111111111111111111111111111111111111111111111111", +); // ↪ 9007199254740991n ``` @@ -34,14 +36,14 @@ const hugeBin = BigInt("0b11111111111111111111111111111111111111111111111111111" 使用 `typeof` 测试时, `BigInt` 对象返回 "bigint" : ```js -typeof 1n === 'bigint'; // true -typeof BigInt('1') === 'bigint'; // true +typeof 1n === "bigint"; // true +typeof BigInt("1") === "bigint"; // true ``` 使用 `Object` 包装后, `BigInt` 被认为是一个普通 "object" : ```js -typeof Object(1n) === 'object'; // true +typeof Object(1n) === "object"; // true ``` ### 运算 @@ -91,29 +93,29 @@ const rounded = 5n / 2n; `BigInt` 和 {{jsxref("Global_Objects/Number", "Number")}} 不是严格相等的,但是宽松相等的。 ```js -0n === 0 +0n === 0; // ↪ false -0n == 0 +0n == 0; // ↪ true ``` {{jsxref("Global_Objects/Number", "Number")}} 和 `BigInt` 可以进行比较。 ```js -1n < 2 +1n < 2; // ↪ true -2n > 1 +2n > 1; // ↪ true -2 > 2 +2 > 2; // ↪ false -2n > 2 +2n > 2; // ↪ false -2n >= 2 +2n >= 2; // ↪ true ``` @@ -134,7 +136,7 @@ mixed.sort(); Object(0n) === Object(0n); // false const o = Object(0n); -o === o // true +o === o; // true ``` ### 条件 @@ -143,29 +145,29 @@ o === o // true ```js if (0n) { - console.log('Hello from the if!'); + console.log("Hello from the if!"); } else { - console.log('Hello from the else!'); + console.log("Hello from the else!"); } // ↪ "Hello from the else!" -0n || 12n +0n || 12n; // ↪ 12n -0n && 12n +0n && 12n; // ↪ 0n -Boolean(0n) +Boolean(0n); // ↪ false -Boolean(12n) +Boolean(12n); // ↪ true -!12n +!12n; // ↪ false -!0n +!0n; // ↪ true ``` @@ -205,7 +207,9 @@ Boolean(12n) 对任何 `BigInt` 值使用 {{jsxref("JSON.stringify()")}} 都会引发 `TypeError`,因为默认情况下 `BigInt` 值不会在 `JSON` 中序列化。但是,如果需要,可以实现 `toJSON` 方法: ```js -BigInt.prototype.toJSON = function() { return this.toString(); } +BigInt.prototype.toJSON = function () { + return this.toString(); +}; ``` `JSON.stringify` 现在生成如下字符串,而不是抛出异常: @@ -243,7 +247,7 @@ function nthPrime(nth) { return prime; } -nthPrime(20n) +nthPrime(20n); // ↪ 73n ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/bigint/tolocalestring/index.md b/files/zh-cn/web/javascript/reference/global_objects/bigint/tolocalestring/index.md index 7ce18bbc630a7c..ad4e7b8f21fa9c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/bigint/tolocalestring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/bigint/tolocalestring/index.md @@ -68,24 +68,24 @@ console.log(bigint.toLocaleString()); const bigint = 123456789123456789n; // 德国使用句号表示千位 -console.log(bigint.toLocaleString('de-DE')); +console.log(bigint.toLocaleString("de-DE")); // 123.456.789.123.456.789 // 大多数说阿拉伯语的阿拉伯国家使用东阿拉伯数字 -console.log(bigint.toLocaleString('ar-EG')); +console.log(bigint.toLocaleString("ar-EG")); // ١٢٣٬٤٥٦٬٧٨٩٬١٢٣٬٤٥٦٬٧٨٩ // 印度使用千、万、千万分隔符 -console.log(bigint.toLocaleString('en-IN')); +console.log(bigint.toLocaleString("en-IN")); // 1,23,45,67,89,12,34,56,789 // nu 扩展键要求使用编号系统,例如中文十进制数 -console.log(bigint.toLocaleString('zh-Hans-CN-u-nu-hanidec')); +console.log(bigint.toLocaleString("zh-Hans-CN-u-nu-hanidec")); // 一二三,四五六,七八九,一二三,四五六,七八九 // 当使用的语言不被支持,例如 // 巴厘岛语,则可以包含一种回退语言,这里以印尼语为例 -console.log(bigint.toLocaleString(['ban', 'id'])); +console.log(bigint.toLocaleString(["ban", "id"])); // 123.456.789.123.456.789 ``` @@ -97,15 +97,19 @@ console.log(bigint.toLocaleString(['ban', 'id'])); const bigint = 123456789123456789n; // 要求使用货币格式 -console.log(bigint.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })); +console.log( + bigint.toLocaleString("de-DE", { style: "currency", currency: "EUR" }), +); // 123.456.789.123.456.789,00 € // 日元不使用小数单位 -console.log(bigint.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' })) +console.log( + bigint.toLocaleString("ja-JP", { style: "currency", currency: "JPY" }), +); // ¥123,456,789,123,456,789 // 保留三位有效数字 -console.log(bigint.toLocaleString('en-IN', { maximumSignificantDigits: 3 })); +console.log(bigint.toLocaleString("en-IN", { maximumSignificantDigits: 3 })); // 1,23,00,00,00,00,00,00,000 ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/bigint/tostring/index.md b/files/zh-cn/web/javascript/reference/global_objects/bigint/tostring/index.md index f3a61efd788bc2..c065e50e4ee439 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/bigint/tostring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/bigint/tostring/index.md @@ -44,11 +44,11 @@ bigIntObj.toString([radix]) ### Using `toString` ```js -17n.toString(); // '17' -66n.toString(2); // '1000010' -254n.toString(16); // 'fe' --10n.toString(2); // -1010' --0xffn.toString(2); // '-11111111' +17n.toString(); // '17' +66n.toString(2); // '1000010' +254n.toString(16); // 'fe' +-10n.toString(2); // -1010' +-0xffn.toString(2); // '-11111111' ``` ### Negative-zero `BigInt` @@ -56,7 +56,7 @@ bigIntObj.toString([radix]) 没有负零 `BigInt`,因为整数中没有负零。`-0.0` 是一个 IEEE 浮点概念,只出现在 JavaScript {{jsxref("Number")}} 类型中。 ```js -(-0n).toString(); // '0' +(-0n).toString(); // '0' BigInt(-0).toString(); // '0' ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/bigint64array/index.md b/files/zh-cn/web/javascript/reference/global_objects/bigint64array/index.md index 3733a006ca3f59..a6df4a168a5252 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/bigint64array/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/bigint64array/index.md @@ -103,7 +103,7 @@ console.log(bigint64.length); // 2 console.log(bigint64.BYTES_PER_ELEMENT); // 8 // From an array -var arr = new BigInt64Array([21n,31n]); +var arr = new BigInt64Array([21n, 31n]); console.log(arr[1]); // 31n // From another TypedArray @@ -116,7 +116,9 @@ var buffer = new ArrayBuffer(32); var z = new BigInt64Array(buffer, 0, 4); // From an iterable -var iterable = function*(){ yield* [1n, 2n, 3n]; }(); +var iterable = (function* () { + yield* [1n, 2n, 3n]; +})(); var bigint64 = new BigInt64Array(iterable); // BigInt64Array[1n, 2n, 3n] ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/biguint64array/index.md b/files/zh-cn/web/javascript/reference/global_objects/biguint64array/index.md index 5c4742d4dc2682..f1e8b70d5373f3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/biguint64array/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/biguint64array/index.md @@ -120,7 +120,7 @@ console.log(biguint64.length); // 2 console.log(biguint64.BYTES_PER_ELEMENT); // 8 // From an array -var arr = new BigUint64Array([21n,31n]); +var arr = new BigUint64Array([21n, 31n]); console.log(arr[1]); // 31n // From another TypedArray @@ -133,7 +133,9 @@ var buffer = new ArrayBuffer(32); var z = new BigUint64Array(buffer, 0, 4); // From an iterable -var iterable = function*(){ yield* [1n, 2n, 3n]; }(); +var iterable = (function* () { + yield* [1n, 2n, 3n]; +})(); var biguint64 = new BigUint64Array(iterable); // BigUint64Array[1n, 2n, 3n] ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/boolean/boolean/index.md b/files/zh-cn/web/javascript/reference/global_objects/boolean/boolean/index.md index 8524374046fa75..165047389035e5 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/boolean/boolean/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/boolean/boolean/index.md @@ -44,11 +44,11 @@ Boolean(value) ```js const bZero = new Boolean(0); const bNull = new Boolean(null); -const bEmptyString = new Boolean(''); +const bEmptyString = new Boolean(""); const bfalse = new Boolean(false); -typeof bfalse // "object" -Boolean(bfalse) // true +typeof bfalse; // "object" +Boolean(bfalse); // true ``` 请注意,用 `Boolean()` 将 `Boolean` 对象转换为原始值的结果总是 `true`,即使该对象的值为 `false`。因此,总是建议避免构造 `Boolean` 包装对象。 @@ -58,16 +58,16 @@ Boolean(bfalse) // true ```js const bfalse = new Boolean(false); -bfalse.valueOf() // false +bfalse.valueOf(); // false ``` ### 使用初始值 true 创建 Boolean 对象 ```js const btrue = new Boolean(true); -const btrueString = new Boolean('true'); -const bfalseString = new Boolean('false'); -const bSuLin = new Boolean('Su Lin'); +const btrueString = new Boolean("true"); +const bfalseString = new Boolean("false"); +const bSuLin = new Boolean("Su Lin"); const bArrayProto = new Boolean([]); const bObjProto = new Boolean({}); ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/boolean/index.md b/files/zh-cn/web/javascript/reference/global_objects/boolean/index.md index 7ee7703621763a..ebe274611b28cd 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/boolean/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/boolean/index.md @@ -34,18 +34,18 @@ if (x) { 不要用创建 `Boolean` 对象的方式将一个非布尔值转化成布尔值,直接将 `Boolean` 当做转换函数来使用即可,或者使用[双重非(!!)运算符](/zh-CN/docs/Web/JavaScript/Reference/Operators/Logical_NOT#double_not_!!): ```js -const x = Boolean(expression); // use this... -const x = !!(expression); // ...or this +const x = Boolean(expression); // use this... +const x = !!expression; // ...or this const x = new Boolean(expression); // don't use this! ``` 对于任何对象,即使是值为 `false` 的 `Boolean` 对象,当将其传给 `Boolean` 函数时,生成的 `Boolean` 对象的值都是 `true`。 ```js -const myFalse = new Boolean(false); // initial value of false -const g = Boolean(myFalse); // initial value of true -const myString = new String('Hello'); // string object -const s = Boolean(myString); // initial value of true +const myFalse = new Boolean(false); // initial value of false +const g = Boolean(myFalse); // initial value of true +const myString = new String("Hello"); // string object +const s = Boolean(myString); // initial value of true ``` 最后,不要在应该使用基本类型布尔值的地方使用 `Boolean` 对象。 @@ -55,8 +55,12 @@ const s = Boolean(myString); // initial value of true 当使用非严格相等(`==`)来比较一个对象和布尔原始值时,最重要的是需要弄明白最终比较的是什么。请看一下的示例: ```js -if ([]) { console.log("[] is truthy")} // logs "[] is truthy" -if ([] == false) { console.log("[] == false")} // logs "[] == false" +if ([]) { + console.log("[] is truthy"); // logs "[] is truthy" +} +if ([] == false) { + console.log("[] == false"); // logs "[] == false" +} ``` `[]` 是真值而 `[] == false` 也同时成立的原因是:非严格比较 `[] == false` 会将 `[]` 的原始值和 `false` 进行比较。而获取 `[]` 的原始值时,JavaScript 引擎会首先调用 `[].toString()`。其结果为 `""`,也是最终和 `false` 一起比较的值。换句话说,`[] == false` 等价于 `"" == false`,而 `""` 是假值——这也解释了为什么会得到这一结果。 @@ -81,7 +85,7 @@ if ([] == false) { console.log("[] == false")} // logs "[] == false" const bNoParam = new Boolean(); const bZero = new Boolean(0); const bNull = new Boolean(null); -const bEmptyString = new Boolean(''); +const bEmptyString = new Boolean(""); const bfalse = new Boolean(false); ``` @@ -89,9 +93,9 @@ const bfalse = new Boolean(false); ```js const btrue = new Boolean(true); -const btrueString = new Boolean('true'); -const bfalseString = new Boolean('false'); -const bSuLin = new Boolean('Su Lin'); +const btrueString = new Boolean("true"); +const bfalseString = new Boolean("false"); +const bSuLin = new Boolean("Su Lin"); const bArrayProto = new Boolean([]); const bObjProto = new Boolean({}); ``` @@ -108,4 +112,4 @@ const bObjProto = new Boolean({}); - [Boolean](/zh-CN/docs/Glossary/Boolean) - [基本类型:布尔类型](/zh-CN/docs/Web/JavaScript/Data_structures#boolean_类型) -- [布尔类型(维基百科)](https://zh.wikipedia.org/wiki/布林_(資料類型)) +- [布尔类型(维基百科)]() diff --git a/files/zh-cn/web/javascript/reference/global_objects/boolean/tostring/index.md b/files/zh-cn/web/javascript/reference/global_objects/boolean/tostring/index.md index d8b726e31d4d50..bccb577eda2988 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/boolean/tostring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/boolean/tostring/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Boolean/toString ## 语法 -```js +```js-nolint toString() ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/boolean/valueof/index.md b/files/zh-cn/web/javascript/reference/global_objects/boolean/valueof/index.md index 6d1780f5b0f639..e8237a77242fc7 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/boolean/valueof/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/boolean/valueof/index.md @@ -31,7 +31,7 @@ bool.valueOf() ```js x = new Boolean(); -myVar = x.valueOf() // assigns false to myVar +myVar = x.valueOf(); // assigns false to myVar ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/dataview/index.md b/files/zh-cn/web/javascript/reference/global_objects/dataview/index.md index b57de2669e6903..e9d0bccddcba10 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/dataview/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/dataview/index.md @@ -30,14 +30,16 @@ console.log(littleEndian); // true 或 false ```js function getUint64(dataview, byteOffset, littleEndian) { // 将 64 位的数字拆分位两个 32 位(4 字节)的部分 - const left = dataview.getUint32(byteOffset, littleEndian); - const right = dataview.getUint32(byteOffset+4, littleEndian); + const left = dataview.getUint32(byteOffset, littleEndian); + const right = dataview.getUint32(byteOffset + 4, littleEndian); // 将两个 32 位的值组合在一起 - const combined = littleEndian? left + 2**32*right : 2**32*left + right; + const combined = littleEndian + ? left + 2 ** 32 * right + : 2 ** 32 * left + right; if (!Number.isSafeInteger(combined)) - console.warn(combined, '超过 MAX_SAFE_INTEGER。可能存在精度丢失。'); + console.warn(combined, "超过 MAX_SAFE_INTEGER。可能存在精度丢失。"); return combined; } @@ -46,14 +48,20 @@ function getUint64(dataview, byteOffset, littleEndian) { 或者,如果你需要完整的 64 位的范围,你可以创建 {{jsxref("BigInt")}}。此外,尽管原生 BigInt 比等效的用户态的库快得多,但由于其大小可变的性质,BigInt 始终比 JavaScript 中的 32 位整数要慢得多。 ```js -const BigInt = window.BigInt, bigThirtyTwo = BigInt(32), bigZero = BigInt(0); +const BigInt = window.BigInt, + bigThirtyTwo = BigInt(32), + bigZero = BigInt(0); function getUint64BigInt(dataview, byteOffset, littleEndian) { // 将 64 位的数字拆分位两个 32 位(4 字节)的部分 - const left = BigInt(dataview.getUint32(byteOffset|0, !!littleEndian)>>>0); - const right = BigInt(dataview.getUint32((byteOffset|0) + 4|0, !!littleEndian)>>>0); + const left = BigInt(dataview.getUint32(byteOffset | 0, !!littleEndian) >>> 0); + const right = BigInt( + dataview.getUint32(((byteOffset | 0) + 4) | 0, !!littleEndian) >>> 0, + ); // 将两个 32 位的值组合在一起并返回该值 - return littleEndian ? (right< **备注:** 如果需要,可以使用{{jsxref("DateTimeFormat", "Intl.DateTimeFormat")}}与一个额外的`options` 参数,从而返回这天的全称(如`"Monday"`).使用此方法,结果会更加国际化: > > ```js -> var options = { weekday: 'long'}; -> console.log(new Intl.DateTimeFormat('en-US', options).format(Xmas95)); +> var options = { weekday: "long" }; +> console.log(new Intl.DateTimeFormat("en-US", options).format(Xmas95)); > // Monday -> console.log(new Intl.DateTimeFormat('de-DE', options).format(Xmas95)); +> console.log(new Intl.DateTimeFormat("de-DE", options).format(Xmas95)); > // Montag > ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/gethours/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/gethours/index.md index fefd35aac102bb..ecea3556113b1b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/gethours/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/gethours/index.md @@ -11,8 +11,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Date/getHours ## 语法 -```js -dateObj.getHours() +```js-nolint +getHours() ``` ### 参数 diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/getmilliseconds/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/getmilliseconds/index.md index 83dae1233653c4..9f4ac77f9c3044 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/getmilliseconds/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/getmilliseconds/index.md @@ -11,8 +11,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Date/getMilliseconds ## 语法 -```js -dateObj.getMilliseconds() +```js-nolint +getMilliseconds() ``` ### 参数 diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/getminutes/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/getminutes/index.md index 93ec15e5c87e64..92ea23561d6e6f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/getminutes/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/getminutes/index.md @@ -11,8 +11,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Date/getMinutes ## 语法 -```js -dateObj.getMinutes() +```js-nolint +getMinutes() ``` ### 参数 diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/getmonth/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/getmonth/index.md index 65469268237063..b943aa39e47f52 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/getmonth/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/getmonth/index.md @@ -11,8 +11,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Date/getMonth ## 语法 -```js -dateObj.getMonth() +```js-nolint +getMonth() ``` ### 参数 @@ -30,7 +30,7 @@ dateObj.getMonth() 下面第二条语句,基于 {{jsxref("Date")}} 对象 Xmas95 的值,把 11 赋值给变量 `month`。 ```js -var Xmas95 = new Date('December 25, 1995 23:15:30'); +var Xmas95 = new Date("December 25, 1995 23:15:30"); var month = Xmas95.getMonth(); console.log(month); // 11 diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/getseconds/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/getseconds/index.md index a40aa56124dfd7..889fa08953ffec 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/getseconds/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/getseconds/index.md @@ -11,8 +11,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Date/getSeconds ## 语法 -```js -dateObj.getSeconds() +```js-nolint +getSeconds() ``` ### 参数 diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/gettimezoneoffset/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/gettimezoneoffset/index.md index 220dbe3988b580..259505c4ea2c5f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/gettimezoneoffset/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/gettimezoneoffset/index.md @@ -11,8 +11,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Date/getTimezoneOffset ## 语法 -```js -dateObj.getTimezoneOffset() +```js-nolint +getTimezoneOffset() ``` ### 参数 diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/index.md index a6497deb0a3ef8..d7bc8ca0368b6a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/index.md @@ -207,8 +207,8 @@ new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds] ```js var today = new Date(); -var birthday = new Date('December 17, 1995 03:24:00'); -var birthday = new Date('1995-12-17T03:24:00'); +var birthday = new Date("December 17, 1995 03:24:00"); +var birthday = new Date("1995-12-17T03:24:00"); var birthday = new Date(1995, 11, 17); var birthday = new Date(1995, 11, 17, 3, 24, 0); ``` @@ -221,9 +221,9 @@ var birthday = new Date(1995, 11, 17, 3, 24, 0); 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) +date.setYear(98); // Sun Feb 01 1998 00:00:00 GMT+0000 (GMT) -date.setFullYear(98); // Sat Feb 01 0098 00:00:00 GMT+0000 (BST) +date.setFullYear(98); // Sat Feb 01 0098 00:00:00 GMT+0000 (BST) ``` ### 计算经过的时间 @@ -254,12 +254,12 @@ var elapsed = end.getTime() - start.getTime(); // 运行时间的毫秒值 ```js // to test a function and get back its return -function printElapsedTime (fTest) { - var nStartTime = Date.now(), - vReturn = fTest(), - nEndTime = Date.now(); - alert("Elapsed time: " + String(nEndTime - nStartTime) + " milliseconds"); - return vReturn; +function printElapsedTime(fTest) { + var nStartTime = Date.now(), + vReturn = fTest(), + nEndTime = Date.now(); + alert("Elapsed time: " + String(nEndTime - nStartTime) + " milliseconds"); + return vReturn; } yourFunctionReturn = printElapsedTime(yourFunction); ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/now/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/now/index.md index 5953f4eab2d5a8..3c05c5e3a79f06 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/now/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/now/index.md @@ -30,13 +30,12 @@ var timeInMs = Date.now(); ```js // reduced time precision (2ms) in Firefox 60 -Date.now() +Date.now(); // 1519211809934 // 1519211810362 // 1519211811670 // ... - // reduced time precision with `privacy.resistFingerprinting` enabled Date.now(); // 1519129853500 diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/parse/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/parse/index.md index 9148cc833284c1..5d354d67f1ca28 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/parse/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/parse/index.md @@ -64,30 +64,30 @@ ECMAScript 规范规定:如果一个字符串不符合标准格式,则函数 ```js // 包含无效值的非 ISO 格式字符串 -new Date('23/25/2014'); +new Date("23/25/2014"); ``` 在 Firefox 30 中会被识别为本地时区的 2015 年 12 月 25 日,而在 Safari 7 中则是无效日期。但是,如果字符串被识别为 ISO 格式并且包含无效值,则在所有遵循 ES5 或者更新标准的浏览器中都会返回 {{jsxref("NaN")}} 。 ```js // 包含无效值的 ISO 格式字符串 -new Date('2014-25-23').toISOString(); +new Date("2014-25-23").toISOString(); // 在所有遵循 ES5 的浏览器中返回 "RangeError: invalid date" ``` SpiderMonkey 的引擎策略可以在 [`jsdate.cpp`](http://mxr.mozilla.org/mozilla-central/source/js/src/jsdate.cpp?rev=64553c483cd1#889) 中找到。字符串 `"10 06 2014"` 可以作为非 ISO 格式字符串使用自定义处理方式的例子。参见这篇关于解析如何进行的[粗略纲要](https://bugzilla.mozilla.org/show_bug.cgi?id=1023155#c6)。 ```js -new Date('10 06 2014'); +new Date("10 06 2014"); ``` 将会被解析为本地时间 2014 年 10 月 6 日,而不是 6 月 10 日。另一个例子 ```js -new Date('foo-bar 2014').toString(); +new Date("foo-bar 2014").toString(); // 返回:"Invalid Date" -Date.parse('foo-bar 2014'); +Date.parse("foo-bar 2014"); // 返回:NaN ``` @@ -98,7 +98,7 @@ Date.parse('foo-bar 2014'); 如果 `IPOdate` 是一个已经存在的 {{jsxref("Date")}} 对象,则可以把其设置为本地时间 1995 年 8 月 9 日。如下: ```js -IPOdate.setTime(Date.parse('Aug 9, 1995')); +IPOdate.setTime(Date.parse("Aug 9, 1995")); ``` 其他一些解析非标准格式日期的例子: diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/setdate/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/setdate/index.md index bb36ad20c10116..85528723245f69 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/setdate/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/setdate/index.md @@ -34,8 +34,8 @@ dateObj.setDate(dayValue) ```js var theBigDay = new Date(1962, 6, 7); // 1962-07-07 -theBigDay.setDate(24); // 1962-07-24 -theBigDay.setDate(32); // 1962-08-01 +theBigDay.setDate(24); // 1962-07-24 +theBigDay.setDate(32); // 1962-08-01 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/setseconds/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/setseconds/index.md index ed10584dc0e35d..383143db5e6c6b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/setseconds/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/setseconds/index.md @@ -40,7 +40,7 @@ dateObj.setSeconds(secondsValue) ```js var theBigDay = new Date(); -theBigDay.setSeconds(30) +theBigDay.setSeconds(30); ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/todatestring/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/todatestring/index.md index 043f6c8e20efe7..363acde2872143 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/todatestring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/todatestring/index.md @@ -28,7 +28,7 @@ The `toDateString` method is especially useful because compliant engines impleme ```js var d = new Date(1993, 6, 28, 14, 39, 7); -println(d.toString()); // prints Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) +println(d.toString()); // prints Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) println(d.toDateString()); // prints Wed Jul 28 1993 ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/toisostring/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/toisostring/index.md index 0c421ab12989f9..0fe7dd96df6019 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/toisostring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/toisostring/index.md @@ -29,28 +29,34 @@ alert(today.toISOString()); // 返回 2011-10-05T14:48:00.000Z 该方法在 ECMA-262 第 5 版中被标准化。对于那些不支持此方法的 JS 引擎可以通过加上下面的代码实现: ```js -if ( !Date.prototype.toISOString ) { - ( function() { - +if (!Date.prototype.toISOString) { + (function () { function pad(number) { - if ( number < 10 ) { - return '0' + number; + if (number < 10) { + return "0" + number; } return number; } - Date.prototype.toISOString = function() { - return this.getUTCFullYear() + - '-' + pad( this.getUTCMonth() + 1 ) + - '-' + pad( this.getUTCDate() ) + - 'T' + pad( this.getUTCHours() ) + - ':' + pad( this.getUTCMinutes() ) + - ':' + pad( this.getUTCSeconds() ) + - '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + - 'Z'; + Date.prototype.toISOString = function () { + return ( + this.getUTCFullYear() + + "-" + + pad(this.getUTCMonth() + 1) + + "-" + + pad(this.getUTCDate()) + + "T" + + pad(this.getUTCHours()) + + ":" + + pad(this.getUTCMinutes()) + + ":" + + pad(this.getUTCSeconds()) + + "." + + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + + "Z" + ); }; - - }() ); + })(); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/tojson/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/tojson/index.md index d84a61ce38b697..cfc6aa6eaac128 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/tojson/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/tojson/index.md @@ -27,7 +27,7 @@ dateObj.toJSON() var date = new Date(); console.log(date); //Thu Nov 09 2017 18:54:04 GMT+0800 (中国标准时间) -var jsonDate = (date).toJSON(); +var jsonDate = date.toJSON(); console.log(jsonDate); //"2017-11-09T10:51:11.395Z" var backToDate = new Date(jsonDate); diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/tostring/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/tostring/index.md index 9e51ce5ad101bc..81770df7e1da90 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/tostring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/tostring/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Date/toString ## 语法 -```js +```js-nolint toString() ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/totimestring/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/totimestring/index.md index 8cd7e0e1e34ebe..5134f94a854ff8 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/totimestring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/totimestring/index.md @@ -28,7 +28,7 @@ The `toTimeString` method is especially useful because compliant engines impleme ```js var d = new Date(1993, 6, 28, 14, 39, 7); -println(d.toString()); // prints Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) +println(d.toString()); // prints Wed Jul 28 1993 14:39:07 GMT-0600 (PDT) println(d.toTimeString()); // prints 14:39:07 GMT-0600 (PDT) ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/utc/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/utc/index.md index cab008e6d64839..568a61f11a2bd4 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/utc/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/utc/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Date/UTC ## 语法 -```js +```js-nolint Date.UTC(year) Date.UTC(year, month) Date.UTC(year, month, day) @@ -24,9 +24,11 @@ Date.UTC(year, month, day, hour, minute, second, millisecond) ## 参数 - `year` + - : 一个表示年份的整数值。 从 `0` 到 `99` 的值会被映射到 `1900` 至 `1999` 年。其他的值则代表实际的年份。参见[示例](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Date#例子:将两位数年份映射为_1900_-_1999_年)。 + - `month` {{optional_inline}} - : `0`(一月)到 `11`(十二月)之间的一个整数,表示月份。从 ECMAScript 2017 开始,如果忽略该值,则默认为 `0`。_(直到 ECMAScript 2016,`month` 都是必须的参数。而从 ES2017 开始,它不再是必须的。)_ - `date` {{optional_inline}} diff --git a/files/zh-cn/web/javascript/reference/global_objects/date/valueof/index.md b/files/zh-cn/web/javascript/reference/global_objects/date/valueof/index.md index 1e768639edc1ee..8f8b102fdb8f66 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/date/valueof/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/date/valueof/index.md @@ -33,7 +33,7 @@ dateObj.valueOf() ```js var x = new Date(56, 6, 17); -var myVar = x.valueOf(); // assigns -424713600000 to myVar +var myVar = x.valueOf(); // assigns -424713600000 to myVar ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/decodeuri/index.md b/files/zh-cn/web/javascript/reference/global_objects/decodeuri/index.md index c4bd528c3ac00d..0a2159625d4777 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/decodeuri/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/decodeuri/index.md @@ -37,7 +37,9 @@ decodeURI(encodedURI) ### 解码一个西里尔字母(Cyrillic)URL ```js -decodeURI("https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"); +decodeURI( + "https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B", +); // "https://developer.mozilla.org/ru/docs/JavaScript_шеллы" ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/decodeuricomponent/index.md b/files/zh-cn/web/javascript/reference/global_objects/decodeuricomponent/index.md index 61373be73c97cd..82244ae3cf9628 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/decodeuricomponent/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/decodeuricomponent/index.md @@ -43,8 +43,8 @@ decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"); ```js try { - var a = decodeURIComponent('%E0%A4%A'); -} catch(e) { + var a = decodeURIComponent("%E0%A4%A"); +} catch (e) { console.error(e); } diff --git a/files/zh-cn/web/javascript/reference/global_objects/encodeuri/index.md b/files/zh-cn/web/javascript/reference/global_objects/encodeuri/index.md index c704ce683e7716..6182bd44d2e238 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/encodeuri/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/encodeuri/index.md @@ -44,20 +44,20 @@ http://username:password@www.example.com:80/path/to/file.php?foo=316&bar=this+ha ```js // 编码高 - 低位完整字符 ok -console.log(encodeURI('\uD800\uDFFF')); +console.log(encodeURI("\uD800\uDFFF")); // 编码单独的高位字符抛出 "Uncaught URIError: URI malformed" -console.log(encodeURI('\uD800')); +console.log(encodeURI("\uD800")); // 编码单独的低位字符抛出 "Uncaught URIError: URI malformed" -console.log(encodeURI('\uDFFF')); +console.log(encodeURI("\uDFFF")); ``` 并且需要注意,如果 URL 需要遵循较新的[RFC3986](http://tools.ietf.org/html/rfc3986)标准,那么方括号是被保留的 (给 IPv6),因此对于那些没有被编码的 URL 部分 (例如主机),可以使用下面的代码: ```js -function fixedEncodeURI (str) { - return encodeURI(str).replace(/%5B/g, '[').replace(/%5D/g, ']'); +function fixedEncodeURI(str) { + return encodeURI(str).replace(/%5B/g, "[").replace(/%5D/g, "]"); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/encodeuricomponent/index.md b/files/zh-cn/web/javascript/reference/global_objects/encodeuricomponent/index.md index cb2ef6c38b0ce5..a46e2773844289 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/encodeuricomponent/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/encodeuricomponent/index.md @@ -36,9 +36,9 @@ encodeURIComponent(str); `encodeURIComponent()` 和 **`encodeURI`** 有以下几个不同点: ```js -var set1 = ";,/?:@&=+$"; // 保留字符 -var set2 = "-_.!~*'()"; // 不转义字符 -var set3 = "#"; // 数字标志 +var set1 = ";,/?:@&=+$"; // 保留字符 +var set2 = "-_.!~*'()"; // 不转义字符 +var set3 = "#"; // 数字标志 var set4 = "ABC abc 123"; // 字母数字字符和空格 console.log(encodeURI(set1)); // ;,/?:@&=+$ @@ -56,13 +56,13 @@ console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (空格被编码为 %2 ```js // 高低位完整 -alert(encodeURIComponent('\uD800\uDFFF')); +alert(encodeURIComponent("\uD800\uDFFF")); // 只有高位,将抛出"URIError: malformed URI sequence" -alert(encodeURIComponent('\uD800')); +alert(encodeURIComponent("\uD800")); // 只有低位,将抛出"URIError: malformed URI sequence" -alert(encodeURIComponent('\uDFFF')); +alert(encodeURIComponent("\uDFFF")); ``` 为了避免服务器收到不可预知的请求,对任何用户输入的作为 URI 部分的内容你都需要用 encodeURIComponent 进行转义。比如,一个用户可能会输入"`Thyme &time=again`"作为`comment`变量的一部分。如果不使用 encodeURIComponent 对此内容进行转义,服务器得到的将是`comment=Thyme%20&time=again`。请注意,"&"符号和"="符号产生了一个新的键值对,所以服务器得到两个键值对(一个键值对是`comment=Thyme`,另一个则是`time=again`),而不是一个键值对。 @@ -72,9 +72,9 @@ alert(encodeURIComponent('\uDFFF')); 为了更严格的遵循 {{rfc("3986")}}(它保留 !, ', (, ), 和 \*),即使这些字符并没有正式划定 URI 的用途,下面这种方式是比较安全的: ```js -function fixedEncodeURIComponent (str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return '%' + c.charCodeAt(0).toString(16).toUpperCase(); +function fixedEncodeURIComponent(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); }); } ``` @@ -84,35 +84,41 @@ function fixedEncodeURIComponent (str) { 下面这个例子提供了 UTF-8 下 {{HTTPHeader("Content-Disposition")}} 和 {{HTTPHeader("Link")}} 的服务器响应头信息的参数(例如 UTF-8 文件名): ```js -var fileName = 'my file(2).txt'; -var header = "Content-Disposition: attachment; filename*=UTF-8''" - + encodeRFC5987ValueChars(fileName); +var fileName = "my file(2).txt"; +var header = + "Content-Disposition: attachment; filename*=UTF-8''" + + encodeRFC5987ValueChars(fileName); console.log(header); // 输出 "Content-Disposition: attachment; filename*=UTF-8''my%20file%282%29.txt" - -function encodeRFC5987ValueChars (str) { - return encodeURIComponent(str). - // 注意,尽管 RFC3986 保留 "!",但 RFC5987 并没有 - // 所以我们并不需要过滤它。 - replace(/['()]/g, escape). // i.e., %27 %28 %29 - replace(/\*/g, '%2A'). - // 下面的并不是 RFC5987 中 URI 编码必须的 - // 所以对于 |`^ 这 3 个字符我们可以稍稍提高一点可读性 - replace(/%(?:7C|60|5E)/g, unescape); +function encodeRFC5987ValueChars(str) { + return ( + encodeURIComponent(str) + // 注意,尽管 RFC3986 保留 "!",但 RFC5987 并没有 + // 所以我们并不需要过滤它。 + .replace(/['()]/g, escape) // i.e., %27 %28 %29 + .replace(/\*/g, "%2A") + // 下面的并不是 RFC5987 中 URI 编码必须的 + // 所以对于 |`^ 这 3 个字符我们可以稍稍提高一点可读性 + .replace(/%(?:7C|60|5E)/g, unescape) + ); } // 以下是上述功能的替换方案 function encodeRFC5987ValueChars2(str) { - return encodeURIComponent(str). - // 注意,尽管 RFC3986 保留 "!",但 RFC5987 并没有, - // 所以我们并不需要过滤它。 - replace(/['()*]/g, c => "%" + c.charCodeAt(0).toString(16)). // i.e., %27 %28 %29 %2a (请注意,"*" 的有效编码是 %2A - // 这需要调用 toUpperCase() 方法来正确编码) - // 以下并不是 RFC5987 编码所必须的, - // 这样我们可以让 |`^ 在网络上获取更好的可读性 - replace(/%(7C|60|5E)/g, (str, hex) => String.fromCharCode(parseInt(hex, 16))); + return ( + encodeURIComponent(str) + // 注意,尽管 RFC3986 保留 "!",但 RFC5987 并没有, + // 所以我们并不需要过滤它。 + .replace(/['()*]/g, (c) => "%" + c.charCodeAt(0).toString(16)) // i.e., %27 %28 %29 %2a (请注意,"*" 的有效编码是 %2A + // 这需要调用 toUpperCase() 方法来正确编码) + // 以下并不是 RFC5987 编码所必须的, + // 这样我们可以让 |`^ 在网络上获取更好的可读性 + .replace(/%(7C|60|5E)/g, (str, hex) => + String.fromCharCode(parseInt(hex, 16)), + ) + ); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/error/cause/index.md b/files/zh-cn/web/javascript/reference/global_objects/error/cause/index.md index 500a2635cea9b9..29d2c25ab64b5a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/error/cause/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/error/cause/index.md @@ -29,7 +29,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Error/cause try { connectToDatabase(); } catch (err) { - throw new Error('Connecting to database failed.', { cause: err }); + throw new Error("Connecting to database failed.", { cause: err }); } ``` @@ -42,14 +42,14 @@ try { ```js function makeRSA(p, q) { if (!Number.isInteger(p) || !Number.isInteger(q)) { - throw new Error('RSA key generation requires integer inputs.', { - cause: { code: 'NonInteger', values: [p, q] }, + throw new Error("RSA key generation requires integer inputs.", { + cause: { code: "NonInteger", values: [p, q] }, }); } if (!areCoprime(p, q)) { - throw new Error('RSA key generation requires two co-prime integers.', { - cause: { code: 'NonCoprime', values: [p, q] }, - }) + throw new Error("RSA key generation requires two co-prime integers.", { + cause: { code: "NonCoprime", values: [p, q] }, + }); } // rsa algorithm… } diff --git a/files/zh-cn/web/javascript/reference/global_objects/error/columnnumber/index.md b/files/zh-cn/web/javascript/reference/global_objects/error/columnnumber/index.md index 9c264b2e1631fd..f685a6948bacb0 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/error/columnnumber/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/error/columnnumber/index.md @@ -12,9 +12,9 @@ slug: Web/JavaScript/Reference/Global_Objects/Error/columnNumber ### 使用 `columnNumber` ```js -var e = new Error('Could not parse input'); +var e = new Error("Could not parse input"); throw e; -console.log(e.columnNumber) // 0 +console.log(e.columnNumber); // 0 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/error/error/index.md b/files/zh-cn/web/javascript/reference/global_objects/error/error/index.md index 3a11c439b92a7f..09ed8338486a02 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/error/error/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/error/error/index.md @@ -68,11 +68,11 @@ try { JavaScript 只有在 `options` 参数为对象时才会尝试读取 `options.cause` 属性,这样可以避免与另一种非标准的 `Error(message, fileName, lineNumber)` 函数签名产生歧义,后者要求第二个参数必须是字符串。如果你省略了 `options` 参数,或者将原始值作为 `options` 传入,又或者传递的对象中没有 `cause` 属性,那么创建的 `Error` 对象将不会包含 `cause` 属性。 ```js -// 省略 options +// 省略 options const error1 = new Error("Error message"); console.log("cause" in error1); // false -// 传递原始值 +// 传递原始值 const error2 = new Error("Error message", ""); console.log("cause" in error2); // false diff --git a/files/zh-cn/web/javascript/reference/global_objects/error/filename/index.md b/files/zh-cn/web/javascript/reference/global_objects/error/filename/index.md index 38e6e51d3cd5c2..61e24f3137d29e 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/error/filename/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/error/filename/index.md @@ -16,7 +16,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Error/fileName ### 使用 `fileName` ```js -var e = new Error('Could not parse input'); +var e = new Error("Could not parse input"); throw e; // e.fileName could look like "file:///C:/example.html" ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/error/index.md b/files/zh-cn/web/javascript/reference/global_objects/error/index.md index 082071e9fd50c8..c31ffded466443 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/error/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/error/index.md @@ -40,9 +40,11 @@ slug: Web/JavaScript/Reference/Global_Objects/Error ## 静态方法 - `Error.captureStackTrace()` {{non-standard_inline}} + - : 一个非标准的 V8 函数,用于在 Error 实例上创建 {{JSxRef("Error.prototype.stack", "stack")}} 属性。 - `Error.stackTraceLimit` {{non-standard_inline}} + - : 一个非标准的 V8 数值属性,用于限制错误堆栈跟踪中包含堆栈帧数量。 - `Error.prepareStackTrace()` {{non-standard_inline}} {{optional_inline}} @@ -78,9 +80,9 @@ slug: Web/JavaScript/Reference/Global_Objects/Error ```js try { - throw new Error('Whoops!') + throw new Error("Whoops!"); } catch (e) { - console.error(e.name + ': ' + e.message) + console.error(e.name + ": " + e.message); } ``` @@ -90,15 +92,14 @@ try { ```js try { - foo.bar() + foo.bar(); } catch (e) { if (e instanceof EvalError) { - console.error(e.name + ': ' + e.message) + console.error(e.name + ": " + e.message); } else if (e instanceof RangeError) { - console.error(e.name + ': ' + e.message) + console.error(e.name + ": " + e.message); } // ... etc - else { // If none of our cases matched leave the Error unhandled throw e; @@ -119,23 +120,23 @@ function doWork() { try { doFailSomeWay(); } catch (err) { - throw new Error('Failed in some way', { cause: err }); + throw new Error("Failed in some way", { cause: err }); } try { doFailAnotherWay(); } catch (err) { - throw new Error('Failed in another way', { cause: err }); + throw new Error("Failed in another way", { cause: err }); } } try { doWork(); } catch (err) { - switch(err.message) { - case 'Failed in some way': + switch (err.message) { + case "Failed in some way": handleFailSomeWay(err.cause); break; - case 'Failed in another way': + case "Failed in another way": handleFailAnotherWay(err.cause); break; } @@ -169,7 +170,7 @@ class MyError extends Error { ```js class CustomError extends Error { - constructor(foo = 'bar', ...params) { + constructor(foo = "bar", ...params) { // Pass remaining arguments (including vendor specific ones) to parent constructor super(...params); @@ -178,7 +179,7 @@ class CustomError extends Error { Error.captureStackTrace(this, CustomError); } - this.name = 'CustomError'; + this.name = "CustomError"; // Custom debugging information this.foo = foo; this.date = new Date(); @@ -186,12 +187,12 @@ class CustomError extends Error { } try { - throw new CustomError('baz', 'bazMessage'); -} catch(e) { - console.error(e.name); // CustomError - console.error(e.foo); // baz + throw new CustomError("baz", "bazMessage"); +} catch (e) { + console.error(e.name); // CustomError + console.error(e.foo); // baz console.error(e.message); // bazMessage - console.error(e.stack); // stacktrace + console.error(e.stack); // stacktrace } ``` @@ -214,11 +215,11 @@ Object.setPrototypeOf(CustomError.prototype, Error.prototype); Object.setPrototypeOf(CustomError, Error); -CustomError.prototype.name = 'CustomError'; +CustomError.prototype.name = "CustomError"; try { - throw new CustomError('baz', 'bazMessage'); -} catch(e) { + throw new CustomError("baz", "bazMessage"); +} catch (e) { console.error(e.name); // CustomError console.error(e.foo); // baz console.error(e.message); // bazMessage diff --git a/files/zh-cn/web/javascript/reference/global_objects/error/linenumber/index.md b/files/zh-cn/web/javascript/reference/global_objects/error/linenumber/index.md index 0652b5b03400b8..639504b9c610dd 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/error/linenumber/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/error/linenumber/index.md @@ -12,18 +12,18 @@ slug: Web/JavaScript/Reference/Global_Objects/Error/lineNumber ### 使用 `lineNumber` ```js -var e = new Error('Could not parse input'); +var e = new Error("Could not parse input"); throw e; -console.log(e.lineNumber) // 2 +console.log(e.lineNumber); // 2 ``` ### 监听 `error` 事件的示例 ```js -window.addEventListener('error', function(e) { +window.addEventListener("error", function (e) { console.log(e.lineNumber); // 5 }); -var e = new Error('Could not parse input'); +var e = new Error("Could not parse input"); throw e; ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/error/name/index.md b/files/zh-cn/web/javascript/reference/global_objects/error/name/index.md index fb1112a5662d83..20a77e54ed0a4c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/error/name/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/error/name/index.md @@ -20,8 +20,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Error/name ```js var e = new Error("Malformed input"); // e.name 默认是"Error" -e.name = "ParseError"; // 修改之后,e.toString() 会成为下面这样的字符串 -throw e; // "ParseError: Malformed input" +e.name = "ParseError"; // 修改之后,e.toString() 会成为下面这样的字符串 +throw e; // "ParseError: Malformed input" ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/error/stack/index.md b/files/zh-cn/web/javascript/reference/global_objects/error/stack/index.md index d6cde09a5cb415..71703012d9b1ce 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/error/stack/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/error/stack/index.md @@ -22,27 +22,27 @@ slug: Web/JavaScript/Reference/Global_Objects/Error/stack 下面这段 html 代码展示了`stack` 属性的使用方法 ```html - - + + Stack Trace Example - + + ``` 假设上面这段代码被保存在 Windows 系统下的 `C:\example.html` 在处理过程中抛出如下所示的错误信息 @@ -81,7 +81,7 @@ Firefox30 以 Gecko 30 格式开头,`Function()` 和 `eval()` 调用产生的 ```js try { - new Function('throw new Error()')(); + new Function("throw new Error()")(); } catch (e) { console.log(e.stack); } @@ -89,7 +89,6 @@ try { // anonymous@file:///C:/example.html line 7 > Function:1:1 // @file:///C:/example.html:7:6 - try { eval("eval('FAIL')"); } catch (x) { diff --git a/files/zh-cn/web/javascript/reference/global_objects/error/tostring/index.md b/files/zh-cn/web/javascript/reference/global_objects/error/tostring/index.md index fccdf26a61a369..eb02a040d60cda 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/error/tostring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/error/tostring/index.md @@ -9,7 +9,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Error/toString ## 语法 -```js +```js-nolint toString() ``` @@ -22,8 +22,8 @@ toString() {{jsxref("Error")}} 对象覆盖了 {{jsxref("Object.prototype.toString()")}} 方法。该方法实现如下(假定 {{jsxref("Object")}} 和 {{jsxref("String")}} 没有被更改): ```js -Error.prototype.toString = function() { - 'use strict'; +Error.prototype.toString = function () { + "use strict"; const obj = Object(this); if (obj !== this) { @@ -31,19 +31,19 @@ Error.prototype.toString = function() { } let name = this.name; - name = (name === undefined) ? 'Error' : String(name); + name = name === undefined ? "Error" : String(name); let msg = this.message; - msg = (msg === undefined) ? '' : String(msg); + msg = msg === undefined ? "" : String(msg); - if (name === '') { + if (name === "") { return msg; } - if (msg === '') { + if (msg === "") { return name; } - return name + ': ' + msg; + return name + ": " + msg; }; ``` @@ -52,24 +52,24 @@ Error.prototype.toString = function() { ### 使用 toString() ```js -const e1 = new Error('fatal error'); +const e1 = new Error("fatal error"); console.log(e1.toString()); // 'Error: fatal error' -const e2 = new Error('fatal error'); +const e2 = new Error("fatal error"); e2.name = undefined; console.log(e2.toString()); // 'Error: fatal error' -const e3 = new Error('fatal error'); -e3.name = ''; +const e3 = new Error("fatal error"); +e3.name = ""; console.log(e3.toString()); // 'fatal error' -const e4 = new Error('fatal error'); -e4.name = ''; +const e4 = new Error("fatal error"); +e4.name = ""; e4.message = undefined; console.log(e4.toString()); // '' -const e5 = new Error('fatal error'); -e5.name = 'hello'; +const e5 = new Error("fatal error"); +e5.name = "hello"; e5.message = undefined; console.log(e5.toString()); // 'hello' ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/escape/index.md b/files/zh-cn/web/javascript/reference/global_objects/escape/index.md index 5dc23dedaaf63a..b06722fb634c49 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/escape/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/escape/index.md @@ -29,12 +29,12 @@ escape(str) ## 示例 ```js -escape("abc123"); // "abc123" -escape("äöü"); // "%E4%F6%FC" -escape("ć"); // "%u0107" +escape("abc123"); // "abc123" +escape("äöü"); // "%E4%F6%FC" +escape("ć"); // "%u0107" // special characters -escape("@*_+-./"); // "@*_+-./" +escape("@*_+-./"); // "@*_+-./" ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/eval/index.md b/files/zh-cn/web/javascript/reference/global_objects/eval/index.md index a62b74843ae8ce..e2141faedf6010 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/eval/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/eval/index.md @@ -36,7 +36,7 @@ eval(string) ```js eval(new String("2 + 2")); // 返回了包含"2 + 2"的字符串对象 -eval("2 + 2"); // returns 4 +eval("2 + 2"); // returns 4 ``` 你可以使用一些通用的方法来绕过这个限制,例如使用 `toString()`。 @@ -50,11 +50,12 @@ eval(expression.toString()); ```js function test() { - var x = 2, y = 4; - console.log(eval('x + y')); // 直接调用,使用本地作用域,结果是 6 + var x = 2, + y = 4; + console.log(eval("x + y")); // 直接调用,使用本地作用域,结果是 6 var geval = eval; // 等价于在全局作用域调用 - console.log(geval('x + y')); // 间接调用,使用全局作用域,throws ReferenceError 因为`x`未定义 - (0, eval)('x + y'); // 另一个间接调用的例子 + console.log(geval("x + y")); // 间接调用,使用全局作用域,throws ReferenceError 因为`x`未定义 + (0, eval)("x + y"); // 另一个间接调用的例子 } ``` @@ -69,37 +70,39 @@ function test() { 使用 eval 的糟糕代码: ```js example-bad -function looseJsonParse(obj){ - return eval("(" + obj + ")"); +function looseJsonParse(obj) { + return eval("(" + obj + ")"); } -console.log(looseJsonParse( - "{a:(4-1), b:function(){}, c:new Date()}" -)) +console.log(looseJsonParse("{a:(4-1), b:function(){}, c:new Date()}")); ``` 不用 eval 的更好的代码: ```js example-good -function looseJsonParse(obj){ - return Function('"use strict";return (' + obj + ')')(); +function looseJsonParse(obj) { + return Function('"use strict";return (' + obj + ")")(); } -console.log(looseJsonParse( - "{a:(4-1), b:function(){}, c:new Date()}" -)) +console.log(looseJsonParse("{a:(4-1), b:function(){}, c:new Date()}")); ``` 比较上面的两个代码片段,两个代码片段似乎是以相同的方式工作,但再想一想:eval 的这个代码的速度要慢得多。注意`c: new Date()`在执行体中。在没有 eval 的函数中,对象在全局范围内被用来进行计算,因此浏览器可以放心的假设 `Date` 是来自 `window.Date` 的而不是一个名为 `Date` 的局部变量。然而,在使用 `eval()` 的代码中,浏览器不能假设这一点,因为如果您的代码是下面这个: ```js example-bad -function Date(n){ - return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0]; +function Date(n) { + return [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", + ][n % 7 || 0]; } -function looseJsonParse(obj){ - return eval("(" + obj + ")"); +function looseJsonParse(obj) { + return eval("(" + obj + ")"); } -console.log(looseJsonParse( - "{a:(4-1), b:function(){}, c:new Date()}" -)) +console.log(looseJsonParse("{a:(4-1), b:function(){}, c:new Date()}")); ``` 因此,在 `eval()` 版本的代码中,浏览器被迫进行高代价的查找调用以检查是否存在名为 `Date()` 的任何局部变量。与 `Function()` 相比,这是非常低效的。 @@ -107,17 +110,21 @@ console.log(looseJsonParse( 在类似的情况下,如果您确实希望能够从 `Function()` 内部的代码调用 `Date` 函数,该怎么办?你应该躲避并退回到 `eval()` 吗?绝对不是,永远不要这么做。而是尝试下面的方法。 ```js example-good -function Date(n){ - return ["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"][n%7 || 0]; +function Date(n) { + return [ + "Monday", + "Tuesday", + "Wednesday", + "Thursday", + "Friday", + "Saturday", + "Sunday", + ][n % 7 || 0]; } -function runCodeWithDateFunction(obj){ - return Function('"use strict";return (' + obj + ')')()( - Date - ); +function runCodeWithDateFunction(obj) { + return Function('"use strict";return (' + obj + ")")()(Date); } -console.log(runCodeWithDateFunction( - "function(Date){ return Date(5) }" -)) +console.log(runCodeWithDateFunction("function(Date){ return Date(5) }")); ``` 由于三重嵌套函数,上面的代码似乎效率低下,但让我们分析一下上述有效方法的好处: @@ -133,8 +140,13 @@ console.log(runCodeWithDateFunction( 最后,我们来看看简化版。使用如上所示的`Function()`,您可以更有效地缩小传递给`runCodeWithDateFunction`的代码字符串,因为函数参数名称也可以缩小,如下面的缩小代码所示。 ```js -console.log(Function('"use strict";return(function(a){return a(5)})')()(function(a){ -return"Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ")[a%7||0]})); +console.log( + Function('"use strict";return(function(a){return a(5)})')()(function (a) { + return "Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split( + " ", + )[a % 7 || 0]; + }), +); ``` 对于常见用例,`eval()`或`Function()`还有更安全 (而且更快!) 的替代方案。 @@ -147,38 +159,38 @@ return"Monday Tuesday Wednesday Thursday Friday Saturday Sunday".split(" ")[a%7| var obj = { a: 20, b: 30 }; var propName = getPropName(); // 返回 "a" 或 "b" -eval( 'var result = obj.' + propsName ) +eval("var result = obj." + propsName); ``` 但是,这里并不是必须得使用 `eval()`。事实上,这里并不建议这样使用。可以使用 [属性访问器](/zh-CN/docs/Web/JavaScript/Reference/Operators/Property_accessors) 进行代替,它更快、更安全: ```js -var obj = { a: 20, b: 30 } +var obj = { a: 20, b: 30 }; var propName = getPropName(); // 返回 "a" 或 "b" -var result = obj[ propName ]; // obj[ "a" ] 与 obj.a 等价 +var result = obj[propName]; // obj[ "a" ] 与 obj.a 等价 ``` 你还可以使用这个方法去访问子代的属性。如下: ```js -var obj = {a: {b: {c: 0}}}; +var obj = { a: { b: { c: 0 } } }; var propPath = getPropPath(); // 例如返回 "a.b.c" -eval( 'var result = obj.' + propPath ) +eval("var result = obj." + propPath); ``` 这里,可以通过分割属性路径、循环遍历不同的属性,来避免 `eval()`: ```js function getDescendantProp(obj, desc) { - var arr = desc.split('.'); + var arr = desc.split("."); while (arr.length) { obj = obj[arr.shift()]; } return obj; } -var obj = {a: {b: {c: 0}}}; +var obj = { a: { b: { c: 0 } } }; var propPath = getPropPath(); // 例如返回 "a.b.c" var result = getDescendantProp(obj, propPath); ``` @@ -187,16 +199,16 @@ var result = getDescendantProp(obj, propPath); ```js function setDescendantProp(obj, desc, value) { - var arr = desc.split('.'); + var arr = desc.split("."); while (arr.length > 1) { obj = obj[arr.shift()]; } - return obj[arr[0]] = value; + return (obj[arr[0]] = value); } -var obj = {a: {b: {c: 0}}}; -var propPath = getPropPath(); // 例如,返回 "a.b.c" -var result = setDescendantProp(obj, propPath, 1); // a.b.c 值为 1 +var obj = { a: { b: { c: 0 } } }; +var propPath = getPropPath(); // 例如,返回 "a.b.c" +var result = setDescendantProp(obj, propPath, 1); // a.b.c 值为 1 ``` ### 使用函数而非代码段 @@ -238,7 +250,7 @@ var x = 2; var y = 39; var z = "42"; eval("x + y + 1"); // returns 42 -eval(z); // returns 42 +eval(z); // returns 42 ``` ### 使用 `eval` 执行一串 JavaScript 语句 @@ -249,7 +261,7 @@ eval(z); // returns 42 var x = 5; var str = "if (x == 5) {console.log('z is 42'); z = 42;} else z = 0;"; -console.log('z is ', eval(str)); +console.log("z is ", eval(str)); ``` 如果您定义了多个值,则会返回最后一个值。 @@ -258,7 +270,7 @@ console.log('z is ', eval(str)); var x = 5; var str = "if (x == 5) {console.log('z is 42'); z = 42; x = 420; } else z = 0;"; -console.log('x is ', eval(str)); // z is 42 x is 420 +console.log("x is ", eval(str)); // z is 42 x is 420 ``` ### 返回值 @@ -266,25 +278,25 @@ console.log('x is ', eval(str)); // z is 42 x is 420 `eval` 返回最后一个表达式的值。 ```js -var str = 'if ( a ) { 1 + 1; } else { 1 + 2; }'; +var str = "if ( a ) { 1 + 1; } else { 1 + 2; }"; var a = true; -var b = eval(str); // returns 2 +var b = eval(str); // returns 2 -console.log('b is : ' + b); +console.log("b is : " + b); a = false; -b = eval(str); // returns 3 +b = eval(str); // returns 3 -console.log('b is : ' + b); +console.log("b is : " + b); ``` ### `eval` 中函数作为字符串被定义需要“(”和“)”作为前缀和后缀 ```js -var fctStr1 = 'function a() {}' -var fctStr2 = '(function a() {})' -var fct1 = eval(fctStr1) // 返回 undefined -var fct2 = eval(fctStr2) // 返回一个函数 +var fctStr1 = "function a() {}"; +var fctStr2 = "(function a() {})"; +var fct1 = eval(fctStr1); // 返回 undefined +var fct2 = eval(fctStr2); // 返回一个函数 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/finalizationregistry/index.md b/files/zh-cn/web/javascript/reference/global_objects/finalizationregistry/index.md index dd2e7f47094e4a..d8305e1e26aa20 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/finalizationregistry/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/finalizationregistry/index.md @@ -16,7 +16,7 @@ slug: Web/JavaScript/Reference/Global_Objects/FinalizationRegistry 你在回调中创建了如下的 registry: ```js -const registry = new FinalizationRegistry(heldValue => { +const registry = new FinalizationRegistry((heldValue) => { // .... }); ``` @@ -95,7 +95,7 @@ Some notes on cleanup callbacks: You create the registry passing in the callback: ```js -const registry = new FinalizationRegistry(heldValue => { +const registry = new FinalizationRegistry((heldValue) => { // .... }); ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/float32array/index.md b/files/zh-cn/web/javascript/reference/global_objects/float32array/index.md index 33550b128158f1..c0bb3302320f2f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/float32array/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/float32array/index.md @@ -119,7 +119,7 @@ console.log(float32.length); // 2 console.log(float32.BYTES_PER_ELEMENT); // 4 // From an array -var arr = new Float32Array([21,31]); +var arr = new Float32Array([21, 31]); console.log(arr[1]); // 31 // From another TypedArray diff --git a/files/zh-cn/web/javascript/reference/global_objects/float64array/index.md b/files/zh-cn/web/javascript/reference/global_objects/float64array/index.md index fddc8694b714e5..ff57d86ce89cd0 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/float64array/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/float64array/index.md @@ -119,7 +119,7 @@ console.log(float64.length); // 2 console.log(float64.BYTES_PER_ELEMENT); // 8 // From an array -var arr = new Float64Array([21,31]); +var arr = new Float64Array([21, 31]); console.log(arr[1]); // 31 // From another TypedArray diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/apply/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/apply/index.md index d03df82f67b39c..52826c6b49bce3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/apply/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/apply/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Function/apply ## 语法 -```js +```js-nolint apply(thisArg) apply(thisArg, argsArray) ``` @@ -57,7 +57,7 @@ apply(thisArg, argsArray) `apply` 正派上用场! ```js -const array = ['a', 'b']; +const array = ["a", "b"]; const elements = [0, 1, 2]; array.push.apply(array, elements); console.info(array); // ["a", "b", 0, 1, 2] @@ -78,13 +78,11 @@ let max = Math.max.apply(null, numbers); // 基本等同于 Math.max(numbers[0], let min = Math.min.apply(null, numbers); // 对比:简单循环算法 -max = -Infinity, min = +Infinity; +(max = -Infinity), (min = +Infinity); for (let i = 0; i < numbers.length; i++) { - if (numbers[i] > max) - max = numbers[i]; - if (numbers[i] < min) - min = numbers[i]; + if (numbers[i] > max) max = numbers[i]; + if (numbers[i] < min) min = numbers[i]; } ``` @@ -100,7 +98,10 @@ function minOfArray(arr) { let QUANTUM = 32768; for (let i = 0, len = arr.length; i < len; i += QUANTUM) { - const submin = Math.min.apply(null, arr.slice(i, Math.min(i + QUANTUM, len))); + const submin = Math.min.apply( + null, + arr.slice(i, Math.min(i + QUANTUM, len)), + ); min = Math.min(submin, min); } @@ -127,16 +128,16 @@ Function.prototype.construct = function (aArgs) { ```js function MyConstructor() { for (let nProp = 0; nProp < arguments.length; nProp++) { - this['property' + nProp] = arguments[nProp]; + this["property" + nProp] = arguments[nProp]; } } -let myArray = [4, 'Hello world!', false]; +let myArray = [4, "Hello world!", false]; let myInstance = MyConstructor.construct(myArray); -console.log(myInstance.property1); // logs 'Hello world!' +console.log(myInstance.property1); // logs 'Hello world!' console.log(myInstance instanceof MyConstructor); // logs 'true' -console.log(myInstance.constructor); // logs 'MyConstructor' +console.log(myInstance.constructor); // logs 'MyConstructor' ``` > **备注:** 这个非原生的 `Function.construct` 方法无法和一些原生构造器(例如 {{jsxref("Global_Objects/Date", "Date")}})一起使用。在这种情况下你必须使用 {{jsxref("Function.prototype.bind")}} 方法。例如,想象有如下一个数组要用在 Date 构造器中:`[2012, 11, 4]`;这时你需要这样写:`new (Function.prototype.bind.apply(Date, [null].concat([2012, 11, 4])))()` ——无论如何这不是最好的实现方式并且也许不该用在任何生产环境中。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/arguments/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/arguments/index.md index 8de4d841502dbf..cb3d66d1ced3b2 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/arguments/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/arguments/index.md @@ -18,17 +18,21 @@ slug: Web/JavaScript/Reference/Global_Objects/Function/arguments ## 示例 ```js -function f(n) { g(n - 1); } +function f(n) { + g(n - 1); +} function g(n) { - console.log('before: ' + g.arguments[0]); - if (n > 0) { f(n); } - console.log('after: ' + g.arguments[0]); + console.log("before: " + g.arguments[0]); + if (n > 0) { + f(n); + } + console.log("after: " + g.arguments[0]); } f(2); -console.log('函数退出后的 arguments 属性值:' + g.arguments); +console.log("函数退出后的 arguments 属性值:" + g.arguments); // 输出: diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/bind/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/bind/index.md index 19373540979207..e3a36e05b67e71 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/bind/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/bind/index.md @@ -47,10 +47,12 @@ function.bind(thisArg[, arg1[, arg2[, ...]]]) `bind()` 最简单的用法是创建一个函数,不论怎么调用,这个函数都有同样的 **`this`** 值。JavaScript 新手经常犯的一个错误是将一个方法从对象中拿出来,然后再调用,期望方法中的 `this` 是原来的对象(比如在回调中传入这个方法)。如果不做特殊处理的话,一般会丢失原来的对象。基于这个函数,用原始的对象创建一个绑定函数,巧妙地解决了这个问题: ```js -this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象 +this.x = 9; // 在浏览器中,this 指向全局的 "window" 对象 var module = { x: 81, - getX: function() { return this.x; } + getX: function () { + return this.x; + }, }; module.getX(); // 81 @@ -75,7 +77,7 @@ function list() { } function addArguments(arg1, arg2) { - return arg1 + arg2 + return arg1 + arg2; } var list1 = list(1, 2, 3); // [1, 2, 3] @@ -111,17 +113,16 @@ function LateBloomer() { } // 在 1 秒钟后声明 bloom -LateBloomer.prototype.bloom = function() { +LateBloomer.prototype.bloom = function () { window.setTimeout(this.declare.bind(this), 1000); }; -LateBloomer.prototype.declare = function() { - console.log('I am a beautiful flower with ' + - this.petalCount + ' petals!'); +LateBloomer.prototype.declare = function () { + console.log("I am a beautiful flower with " + this.petalCount + " petals!"); }; var flower = new LateBloomer(); -flower.bloom(); // 一秒钟后,调用 'declare' 方法 +flower.bloom(); // 一秒钟后,调用 'declare' 方法 ``` ### 作为构造函数使用的绑定函数 @@ -136,20 +137,20 @@ function Point(x, y) { this.y = y; } -Point.prototype.toString = function() { - return this.x + ',' + this.y; +Point.prototype.toString = function () { + return this.x + "," + this.y; }; var p = new Point(1, 2); p.toString(); // '1,2' var emptyObj = {}; -var YAxisPoint = Point.bind(emptyObj, 0/*x*/); +var YAxisPoint = Point.bind(emptyObj, 0 /*x*/); // 本页下方的 polyfill 不支持运行这行代码, // 但使用原生的 bind 方法运行是没问题的: -var YAxisPoint = Point.bind(null, 0/*x*/); +var YAxisPoint = Point.bind(null, 0 /*x*/); /*(译注:polyfill 的 bind 方法中,如果把 bind 的第一个参数加上, 即对新绑定的 this 执行 Object(this),包装为对象, @@ -173,7 +174,7 @@ new YAxisPoint(17, 42) instanceof Point; // true //(即使通常来说这个不是被期望发生的) YAxisPoint(13); -emptyObj.x + ',' + emptyObj.y; // '0,13' +emptyObj.x + "," + emptyObj.y; // '0,13' ``` 如果你希望一个绑定函数要么只能用 {{jsxref("Operators/new", "new")}} 操作符,要么只能直接调用,那你必须在目标函数上显式规定这个限制。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/call/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/call/index.md index 37806a32e215d2..d9e997680a31f9 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/call/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/call/index.md @@ -48,16 +48,16 @@ function Product(name, price) { function Food(name, price) { Product.call(this, name, price); - this.category = 'food'; + this.category = "food"; } function Toy(name, price) { Product.call(this, name, price); - this.category = 'toy'; + this.category = "toy"; } -var cheese = new Food('feta', 5); -var fun = new Toy('robot', 40); +var cheese = new Food("feta", 5); +var fun = new Toy("robot", 40); ``` ### 使用 `call` 方法调用匿名函数 @@ -66,16 +66,15 @@ var fun = new Toy('robot', 40); ```js var animals = [ - { species: 'Lion', name: 'King' }, - { species: 'Whale', name: 'Fail' } + { species: "Lion", name: "King" }, + { species: "Whale", name: "Fail" }, ]; for (var i = 0; i < animals.length; i++) { - (function(i) { - this.print = function() { - console.log('#' + i + ' ' + this.species - + ': ' + this.name); - } + (function (i) { + this.print = function () { + console.log("#" + i + " " + this.species + ": " + this.name); + }; this.print(); }).call(animals[i], i); } @@ -87,15 +86,18 @@ for (var i = 0; i < animals.length; i++) { ```js function greet() { - var reply = [this.animal, 'typically sleep between', this.sleepDuration].join(' '); + var reply = [this.animal, "typically sleep between", this.sleepDuration].join( + " ", + ); console.log(reply); } var obj = { - animal: 'cats', sleepDuration: '12 and 16 hours' + animal: "cats", + sleepDuration: "12 and 16 hours", }; -greet.call(obj); // cats typically sleep between 12 and 16 hours +greet.call(obj); // cats typically sleep between 12 and 16 hours ``` ### 使用 **`call`** 方法调用函数并且不指定第一个参数(`argument`) @@ -103,24 +105,24 @@ greet.call(obj); // cats typically sleep between 12 and 16 hours 在下面的例子中,我们调用了 `display` 方法,但并没有传递它的第一个参数。如果没有传递第一个参数,`this` 的值将会被绑定为全局对象。 ```js -var sData = 'Wisen'; +var sData = "Wisen"; function display() { - console.log('sData value is %s ', this.sData); + console.log("sData value is %s ", this.sData); } -display.call(); // sData value is Wisen +display.call(); // sData value is Wisen ``` > **备注:** 在严格模式下,`this` 的值将会是 `undefined`。见下文。 ```js -'use strict'; +"use strict"; -var sData = 'Wisen'; +var sData = "Wisen"; function display() { - console.log('sData value is %s ', this.sData); + console.log("sData value is %s ", this.sData); } display.call(); // Cannot read the property of 'sData' of undefined diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/caller/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/caller/index.md index 8566e0c2793c32..b337aa38896523 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/caller/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/caller/index.md @@ -22,9 +22,14 @@ slug: Web/JavaScript/Reference/Global_Objects/Function/caller 注意,在使用递归调用时,你不能使用此属性来重现出调用栈。请考虑以下代码: ```js -function f(n) { g(n-1) } -function g(n) { if(n>0) f(n); else stop() } -f(2) +function f(n) { + g(n - 1); +} +function g(n) { + if (n > 0) f(n); + else stop(); +} +f(2); ``` 当 `stop()` 函数被调用时,调用栈是这样的: @@ -36,7 +41,7 @@ f(2) -> g(1) -> f(1) -> g(0) -> stop() 由于下面的表达式为 true (只保留函数最后一次被调用时的 caller): ```js -stop.caller === g && f.caller === g && g.caller === f +stop.caller === g && f.caller === g && g.caller === f; ``` 所以如果你尝试在 `stop()` 函数中获取调用栈的话: @@ -62,10 +67,9 @@ while (f) { ```js function myFunc() { - if (myFunc.caller == null) { - return ("该函数在全局作用域内被调用!"); - } else - return ("调用我的是函数是" + myFunc.caller); + if (myFunc.caller == null) { + return "该函数在全局作用域内被调用!"; + } else return "调用我的是函数是" + myFunc.caller; } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/displayname/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/displayname/index.md index ca826d7f74953f..cd5b620a61a9b4 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/displayname/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/displayname/index.md @@ -16,9 +16,11 @@ function doSomething() {} console.log(doSomething.displayName); // "undefined" -var popup = function(content) { console.log(content); }; +var popup = function (content) { + console.log(content); +}; -popup.displayName = 'Show Popup'; +popup.displayName = "Show Popup"; console.log(popup.displayName); // "Show Popup" ``` @@ -27,14 +29,18 @@ console.log(popup.displayName); // "Show Popup" ```js var object = { - someMethod: function() {} + someMethod: function () {}, }; -object.someMethod.displayName = 'someMethod'; +object.someMethod.displayName = "someMethod"; console.log(object.someMethod.displayName); // logs "someMethod" -try { someMethod } catch(e) { console.log(e); } +try { + someMethod; +} catch (e) { + console.log(e); +} // ReferenceError: someMethod is not defined ``` @@ -43,14 +49,14 @@ try { someMethod } catch(e) { console.log(e); } ```js var object = { // anonymous - someMethod: function(value) { - arguments.callee.displayName = 'someMethod (' + value + ')'; - } + someMethod: function (value) { + arguments.callee.displayName = "someMethod (" + value + ")"; + }, }; console.log(object.someMethod.displayName); // "undefined" -object.someMethod('123') +object.someMethod("123"); console.log(object.someMethod.displayName); // "someMethod (123)" ``` @@ -61,8 +67,8 @@ console.log(object.someMethod.displayName); // "someMethod (123)" 通过如下的举例,显示的名称应该显示像"function My Function()" ```js -var a = function() {}; -a.displayName = 'My Function'; +var a = function () {}; +a.displayName = "My Function"; a; // "function My Function()" ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/function/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/function/index.md index 04f4e4923df086..8f2e4edb20e14f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/function/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/function/index.md @@ -46,7 +46,7 @@ Function(arg0, arg1, /* … ,*/ argN, functionBody) `function anonymous(${args.join(",")} ) { ${functionBody} -}` +}`; ``` 这可以通过调用函数的 [`toString()`](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/toString) 方法来观察。 @@ -54,7 +54,9 @@ ${functionBody} 然而,与普通的[函数表达式](/zh-CN/docs/Web/JavaScript/Reference/Operators/function)不同,`anonymous` 这个名字不会被添加到 `functionBody` 的作用域中,因为 `functionBody` 只能访问全局作用域。如果 `functionBody` 不在[严格模式](/zh-CN/docs/Web/JavaScript/Reference/Strict_mode)中(主体本身需要有 `"use strict"` 指令,因为它不从上下文中继承严格性),你可以使用 [`arguments.callee`](/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments/callee) 来指代函数本身。另外,你可以将递归部分定义为一个内部函数: ```js -const recursiveFn = new Function("count", ` +const recursiveFn = new Function( + "count", + ` (function recursiveFn(count) { if (count < 0) { return; @@ -62,7 +64,8 @@ const recursiveFn = new Function("count", ` console.log(count); recursiveFn(count - 1); })(count); -`); +`, +); ``` 请注意,集合源的两个动态部分——参数列表 `args.join(",")` 和 `functionBody` 将首先被分别解析,以确保它们在语法上都是有效的。这可以防止类似注入的尝试。 @@ -83,7 +86,7 @@ new Function("/*", "*/) {"); // 此示例可在你的 JavaScript 控制台下运行 // 创建一个接受两个参数的函数,并返回这些参数的和 -const adder = new Function('a', 'b', 'return a + b'); +const adder = new Function("a", "b", "return a + b"); // 调用函数 adder(2, 6); @@ -98,23 +101,29 @@ adder(2, 6); // 函数构造器可以接受多个分号分隔的语句。Function 表达式需要带有函数的返回语句 // 观察一下,new Function 被调用了。这样我们就可以在事后直接调用我们创建的函数了 -const sumOfArray = new Function('const sumArray = (arr) => arr.reduce((previousValue, currentValue) => previousValue + currentValue); return sumArray')(); +const sumOfArray = new Function( + "const sumArray = (arr) => arr.reduce((previousValue, currentValue) => previousValue + currentValue); return sumArray", +)(); // 调用函数 sumOfArray([1, 2, 3, 4]); // 10 // 如果你不在创建函数时调用 new Function,你可以使用 Function.call() 方法来调用它 -const findLargestNumber = new Function('function findLargestNumber (arr) { return Math.max(...arr) }; return findLargestNumber'); +const findLargestNumber = new Function( + "function findLargestNumber (arr) { return Math.max(...arr) }; return findLargestNumber", +); // 调用函数 findLargestNumber.call({}).call({}, [2, 4, 1, 8, 5]); // 8 // 函数声明不需要返回语句 -const sayHello = new Function('return function (name) { return `Hello, ${name}` }')(); +const sayHello = new Function( + "return function (name) { return `Hello, ${name}` }", +)(); // 调用函数 -sayHello('world'); +sayHello("world"); // Hello, world ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/index.md index 1374c9b0af9c9c..87dfe8b17a27d6 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/index.md @@ -46,22 +46,22 @@ slug: Web/JavaScript/Reference/Global_Objects/Function var x = 10; function createFunction1() { - var x = 20; - return new Function('return x;'); // 这里的 x 指向最上面全局作用域内的 x + var x = 20; + return new Function("return x;"); // 这里的 x 指向最上面全局作用域内的 x } function createFunction2() { - var x = 20; - function f() { - return x; // 这里的 x 指向上方本地作用域内的 x - } - return f; + var x = 20; + function f() { + return x; // 这里的 x 指向上方本地作用域内的 x + } + return f; } var f1 = createFunction1(); -console.log(f1()); // 10 +console.log(f1()); // 10 var f2 = createFunction2(); -console.log(f2()); // 20 +console.log(f2()); // 20 ``` 虽然这段代码可以在浏览器中正常运行,但在 Node.js 中 `f1()` 会产生一个“找不到变量 `x`”的 `ReferenceError`。这是因为在 Node 中顶级作用域不是全局作用域,而 `x` 其实是在当前模块的作用域之中。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/name/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/name/index.md index 8d9dfa5d89a553..4e7322bb43dffb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/name/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/name/index.md @@ -20,7 +20,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Function/name ```js function someFunction() {} -someFunction.name = 'otherFunction'; +someFunction.name = "otherFunction"; console.log(someFunction.name); // someFunction ``` @@ -35,8 +35,8 @@ console.log(someFunction.name); // someFunction `name` 属性会返回函数的名称。 ```js -function doSomething() { } -doSomething.name; // "doSomething" +function doSomething() {} +doSomething.name; // "doSomething" ``` ### 构造函数的名称 @@ -44,7 +44,7 @@ doSomething.name; // "doSomething" 使用`new Function(...)`语法创建的函数或只是 `Function(...) create` {{jsxref("Function")}}对象及其名称为“anonymous”。 ```js -(new Function).name; // "anonymous" +new Function().name; // "anonymous" ``` ### 推断函数名称 @@ -52,9 +52,9 @@ doSomething.name; // "doSomething" 变量和方法可以从句法位置推断匿名函数的名称(ECMAScript 2015 中新增)。 ```js -var f = function() {}; +var f = function () {}; var object = { - someMethod: function() {} + someMethod: function () {}, }; console.log(f.name); // "f" @@ -65,12 +65,16 @@ console.log(object.someMethod.name); // "someMethod" ```js var object = { - someMethod: function object_someMethod() {} + someMethod: function object_someMethod() {}, }; console.log(object.someMethod.name); // "object_someMethod" -try { object_someMethod } catch(e) { alert(e); } +try { + object_someMethod; +} catch (e) { + alert(e); +} // ReferenceError: object_someMethod is not defined ``` @@ -79,10 +83,10 @@ try { object_someMethod } catch(e) { alert(e); } ```js var object = { // anonymous - someMethod: function() {} + someMethod: function () {}, }; -object.someMethod.name = 'otherMethod'; +object.someMethod.name = "otherMethod"; console.log(object.someMethod.name); // someMethod ``` @@ -92,7 +96,7 @@ console.log(object.someMethod.name); // someMethod ```js var o = { - foo(){} + foo() {}, }; o.foo.name; // "foo"; ``` @@ -102,7 +106,7 @@ o.foo.name; // "foo"; {{jsxref("Function.bind()")}} 所创建的函数将会在函数的名称前加上"bound " 。 ```js -function foo() {}; +function foo() {} foo.bind({}).name; // "bound foo" ``` @@ -112,8 +116,8 @@ foo.bind({}).name; // "bound foo" ```js var o = { - get foo(){}, - set foo(x){} + get foo() {}, + set foo(x) {}, }; var descriptor = Object.getOwnPropertyDescriptor(o, "foo"); @@ -126,7 +130,7 @@ descriptor.set.name; // "set foo"; 你可以使用`obj.constructor.name`来检查对象的“类”(但请务必阅读以下警告): ```js -function Foo() {} // ES2015 Syntax: class Foo {} +function Foo() {} // ES2015 Syntax: class Foo {} var fooInstance = new Foo(); console.log(fooInstance.constructor.name); // logs "Foo" @@ -147,8 +151,8 @@ class Foo { ```js function Foo() {} -Object.defineProperty(Foo, 'name', { writable: true }); -Foo.name = function() {}; +Object.defineProperty(Foo, "name", { writable: true }); +Foo.name = function () {}; ``` 通过`fooInstance.constructor.name`获取`fooInstance`类不会给我们所有的类名,而是静态类方法的引用。例如: @@ -161,7 +165,7 @@ console.log(fooInstance.constructor.name); // logs function name() 你也可以从 ES5 语法示例中看到,在 Chrome 或 Firefox 的中静态定义的`Foo.name`变得可写。内置定义在没有自定义静态定义时是只读的: ```js -Foo.name = 'Hello'; +Foo.name = "Hello"; console.log(Foo.name); //如果 Foo 具有静态 name() 属性,则输出“Hello”,否则为“Foo” ``` @@ -176,8 +180,8 @@ console.log(Foo.name); var sym1 = Symbol("foo"); var sym2 = Symbol(); var o = { - [sym1]: function(){}, - [sym2]: function(){} + [sym1]: function () {}, + [sym2]: function () {}, }; o[sym1].name; // "[foo]" @@ -191,25 +195,25 @@ o[sym2].name; // "" 例如下面的代码: ```js -function Foo() {}; +function Foo() {} var foo = new Foo(); -if (foo.constructor.name === 'Foo') { +if (foo.constructor.name === "Foo") { console.log("'foo' is an instance of 'Foo'"); } else { - console.log('Oops!'); + console.log("Oops!"); } ``` 可能被压缩为: ```js -function a() {}; +function a() {} var b = new a(); -if (b.constructor.name === 'Foo') { +if (b.constructor.name === "Foo") { console.log("'foo' is an instance of 'Foo'"); } else { - console.log('Oops!'); + console.log("Oops!"); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/prototype/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/prototype/index.md index c0fdac22b9985f..a3e24c439b742c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/prototype/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/prototype/index.md @@ -25,7 +25,7 @@ console.log(Object.getPrototypeOf(inst) === Ctor.prototype); // true 关于构造函数的 `prototype` 属性与结果对象的原型之间的相互作用,你可以查看[继承与原型链](/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#构造函数)来了解更多。 -一个具有 `prototype` 属性的函数也并不代表其有资格作为构造函数。例如,[function*](/zh-CN/docs/Web/JavaScript/Reference/Statements/function*) 拥有 `prototype` 属性,但它不能通过 `new` 运算符来调用。 +一个具有 `prototype` 属性的函数也并不代表其有资格作为构造函数。例如,[function\*](/zh-CN/docs/Web/JavaScript/Reference/Statements/function*) 拥有 `prototype` 属性,但它不能通过 `new` 运算符来调用。 ```js async function* asyncGeneratorFunction() {} diff --git a/files/zh-cn/web/javascript/reference/global_objects/function/tostring/index.md b/files/zh-cn/web/javascript/reference/global_objects/function/tostring/index.md index 767288dad4daec..3e3d2e4dbd57b8 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/function/tostring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/function/tostring/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Function/toString ## 语法 -```js +```js-nolint toString() ``` @@ -28,13 +28,13 @@ toString() 若 `this` 不是 `Function` 对象,则 `toString()` 方法将抛出 {{jsxref("TypeError")}}("Function.prototype.toString called on incompatible object")异常。 ```js example-bad -Function.prototype.toString.call('foo'); // throws TypeError +Function.prototype.toString.call("foo"); // throws TypeError ``` 如果是在内置函数或由 `Function.prototype.bind` 返回的函数上调用 `toString()`,则`toString()` 返回原生代码字符串,如下 ```js -"function someName() { [native code] }" +"function someName() { [native code] }"; ``` 对于内部对象方法和函数,`someName` 是函数的初始名称;否则其可能是实现定义(implementation-defined)的,但始终以属性名称语法的形式呈现,如:`[1 + 1]`、`someName` 或 `1`。 @@ -44,7 +44,7 @@ Function.prototype.toString.call('foo'); // throws TypeError 若是在由 `Function` 构造函数生成的函数上调用 `toString()`,则 `toString()` 返回创建后的函数源码,包括形参和函数体,函数名为“anonymous”。例如:对于 `Function("a", "b", "return a + b").toString()`,则会返回: ```js -"function anonymous(a,b\n) {\nreturn a + b\n}" +"function anonymous(a,b\n) {\nreturn a + b\n}"; ``` 从 ES2018 开始,规范要求 `toString()` 的返回值与声明的源代码完全相同,包括空格和注释;或者因某种原因,主机没有源代码,则要求返回一个原生函数字符串。参见[兼容性表格](#浏览器兼容性)以查询对这一修改后的行为的支持情况。 @@ -59,7 +59,9 @@ function test(fn) { } function f() {} -class A { a() {} } +class A { + a() {} +} function* g() {} test(f); // "function f() {}" @@ -68,13 +70,23 @@ test(g); // "function* g() {}" test((a) => a); // "(a) => a" test({ a() {} }.a); // "a() {}" test({ *a() {} }.a); // "*a() {}" -test({ [0](){} }[0]); // "[0]() {}" -test(Object.getOwnPropertyDescriptor({ - get a() {}, -}, "a").get); // "get a() {}" -test(Object.getOwnPropertyDescriptor({ - set a(x) {}, -}, "a").set); // "set a(x) {}" +test({ [0]() {} }[0]); // "[0]() {}" +test( + Object.getOwnPropertyDescriptor( + { + get a() {}, + }, + "a", + ).get, +); // "get a() {}" +test( + Object.getOwnPropertyDescriptor( + { + set a(x) {}, + }, + "a", + ).set, +); // "set a(x) {}" test(Function.prototype.toString); // "function toString() { [native code] }" test(function f() {}.bind(0)); // "function () { [native code] }" test(Function("a", "b")); // function anonymous(a\n) {\nb\n} @@ -87,14 +99,18 @@ test(Function("a", "b")); // function anonymous(a\n) {\nb\n} 可以通过将函数强制转换为字符串来获取函数的源文本——例如,通过将其包装在模板字符串中: ```js -function foo() { return 'bar' } +function foo() { + return "bar"; +} console.log(`${foo}`); // "function foo() { return 'bar' }" ``` 得到的源文本是*准确的*,包括其中的注释(否则引擎的内部表示不会存储这些注释)。 ```js -function foo/* a comment */() { return 'bar' } +function foo /* a comment */() { + return "bar"; +} console.log(foo.toString()); // "function foo/* a comment */() { return 'bar' }" ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/generator/next/index.md b/files/zh-cn/web/javascript/reference/global_objects/generator/next/index.md index cb2782f0f572c7..3b4799e2ac2661 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/generator/next/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/generator/next/index.md @@ -43,10 +43,10 @@ function* gen() { } var g = gen(); // "Generator { }" -g.next(); // "Object { value: 1, done: false }" -g.next(); // "Object { value: 2, done: false }" -g.next(); // "Object { value: 3, done: false }" -g.next(); // "Object { value: undefined, done: true }" +g.next(); // "Object { value: 1, done: false }" +g.next(); // "Object { value: 2, done: false }" +g.next(); // "Object { value: 3, done: false }" +g.next(); // "Object { value: undefined, done: true }" ``` ### 向生成器传值 diff --git a/files/zh-cn/web/javascript/reference/global_objects/generator/return/index.md b/files/zh-cn/web/javascript/reference/global_objects/generator/return/index.md index c8acc01df27b62..426cad819e3b21 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/generator/return/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/generator/return/index.md @@ -37,9 +37,9 @@ function* gen() { var g = gen(); -g.next(); // { value: 1, done: false } +g.next(); // { value: 1, done: false } g.return("foo"); // { value: "foo", done: true } -g.next(); // { value: undefined, done: true } +g.next(); // { value: undefined, done: true } ``` 如果对已经处于“完成”状态的生成器调用`return(value)`,则生成器将保持在“完成”状态。如果没有提供参数,则返回对象的`value`属性与示例最后的`.next()`方法相同。如果提供了参数,则参数将被设置为返回对象的`value`属性的值。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/generator/throw/index.md b/files/zh-cn/web/javascript/reference/global_objects/generator/throw/index.md index 6aa243049d69a2..1428eebe2f69a9 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/generator/throw/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/generator/throw/index.md @@ -37,10 +37,10 @@ gen.throw(exception) ```js function* gen() { - while(true) { + while (true) { try { - yield 42; - } catch(e) { + yield 42; + } catch (e) { console.log("Error caught!"); } } diff --git a/files/zh-cn/web/javascript/reference/global_objects/generatorfunction/index.md b/files/zh-cn/web/javascript/reference/global_objects/generatorfunction/index.md index 9f94644f665904..a9707684ead4b6 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/generatorfunction/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/generatorfunction/index.md @@ -30,9 +30,11 @@ GeneratorFunction(arg0, arg1, /* … ,*/ argN, functionBody) ### 参数 - `argN` {{optional_inline}} + - : 函数的参数名,它们必须是符合 JavaScript 参数规范(任何[标识符](/zh-CN/docs/Glossary/Identifier)、[剩余参数](/zh-CN/docs/Web/JavaScript/Reference/Functions/rest_parameters)或[解构](/zh-CN/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment)参数,以及可选的默认参数值)的字符串。 由于参数的解析方式与函数声明相同,参数中接受空格和注释。例如:`"x", "theValue = 42", "[a, b] /* numbers */"` 或 `"x, theValue = 42, [a, b] /* numbers */"`。(`"x, theValue = 42", "[a, b]"` 也是正确的,但这容易造成困扰。) + - `functionBody` - : 包含 JavaScript 语句的{{jsxref("String", "字符串", "", 1)}},这些语句组成了新函数的定义。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/globalthis/index.md b/files/zh-cn/web/javascript/reference/global_objects/globalthis/index.md index f831aa19ab6f54..1fa1b360e886c3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/globalthis/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/globalthis/index.md @@ -39,15 +39,21 @@ globalThis ```js var getGlobal = function () { - if (typeof self !== 'undefined') { return self; } - if (typeof window !== 'undefined') { return window; } - if (typeof global !== 'undefined') { return global; } - throw new Error('unable to locate global object'); + if (typeof self !== "undefined") { + return self; + } + if (typeof window !== "undefined") { + return window; + } + if (typeof global !== "undefined") { + return global; + } + throw new Error("unable to locate global object"); }; var globals = getGlobal(); -if (typeof globals.setTimeout !== 'function') { +if (typeof globals.setTimeout !== "function") { // 此环境中没有 setTimeout 方法! } ``` @@ -55,7 +61,7 @@ if (typeof globals.setTimeout !== 'function') { 但是有了 `globalThis` 之后,只需要: ```js -if (typeof globalThis.setTimeout !== 'function') { +if (typeof globalThis.setTimeout !== "function") { // 此环境中没有 setTimeout 方法! } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/int16array/index.md b/files/zh-cn/web/javascript/reference/global_objects/int16array/index.md index e3278212883752..540f8ed42729c9 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/int16array/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/int16array/index.md @@ -119,7 +119,7 @@ console.log(int16.length); // 2 console.log(int16.BYTES_PER_ELEMENT); // 2 // From an array -var arr = new Int16Array([21,31]); +var arr = new Int16Array([21, 31]); console.log(arr[1]); // 31 // From another TypedArray diff --git a/files/zh-cn/web/javascript/reference/global_objects/int32array/index.md b/files/zh-cn/web/javascript/reference/global_objects/int32array/index.md index 78b1c080fefb29..d740470f84fd81 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/int32array/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/int32array/index.md @@ -121,7 +121,7 @@ console.log(int32.length); // 2 console.log(int32.BYTES_PER_ELEMENT); // 4 // 从一个数组 -var arr = new Int32Array([21,31]); +var arr = new Int32Array([21, 31]); console.log(arr[1]); // 31 // 从一个其他 TypedArray diff --git a/files/zh-cn/web/javascript/reference/global_objects/int8array/index.md b/files/zh-cn/web/javascript/reference/global_objects/int8array/index.md index 66bccacfc6b30a..a9846446ba33eb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/int8array/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/int8array/index.md @@ -119,7 +119,7 @@ console.log(int8.length); // 2 console.log(int8.BYTES_PER_ELEMENT); // 1 // 以数组构造对象 -var arr = new Int8Array([21,31]); +var arr = new Int8Array([21, 31]); console.log(arr[1]); // 31 // 从另一数组构造对象 diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/datetimeformat/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/datetimeformat/index.md index 21915818f58332..06f7faced4f6a9 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/datetimeformat/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/datetimeformat/index.md @@ -56,29 +56,29 @@ const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // 假定下面输出的结果使用了洛杉矶时区(UTC-0800,太平洋标准时间) // 美式英语 (US English) 使用 month-day-year 格式 -console.log(new Intl.DateTimeFormat('en-US').format(date)); +console.log(new Intl.DateTimeFormat("en-US").format(date)); // "12/19/2012" // 英式英语 (British English) 使用 day-month-year 格式 -console.log(new Intl.DateTimeFormat('en-GB').format(date)); +console.log(new Intl.DateTimeFormat("en-GB").format(date)); // "19/12/2012" // 韩国使用 year-month-day 格式 -console.log(new Intl.DateTimeFormat('ko-KR').format(date)); +console.log(new Intl.DateTimeFormat("ko-KR").format(date)); // "2012. 12. 19." // 大部分阿拉伯国家使用阿拉伯字母 (real Arabic digits) -console.log(new Intl.DateTimeFormat('ar-EG').format(date)); +console.log(new Intl.DateTimeFormat("ar-EG").format(date)); // "١٩‏/١٢‏/٢٠١٢" // 在日本,应用可能想要使用日本日历, // 2012 年是平成 24 年(平成是是日本天皇明仁的年号,由 1989 年 1 月 8 日起开始计算直至现在) -console.log(new Intl.DateTimeFormat('ja-JP-u-ca-japanese').format(date)); +console.log(new Intl.DateTimeFormat("ja-JP-u-ca-japanese").format(date)); // "24/12/19" // 当请求可能不支持的语言,如巴厘语(ban)时,若同时指定了备用的语言, // 那么将使用备用的语言输出(本例为印尼语(id)) -console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date)); +console.log(new Intl.DateTimeFormat(["ban", "id"]).format(date)); // "19/12/2012" ``` @@ -90,54 +90,65 @@ console.log(new Intl.DateTimeFormat(['ban', 'id']).format(date)); const date = new Date(Date.UTC(2012, 11, 20, 3, 0, 0)); // 请求参数 (options) 中包含参数星期 (weekday),并且该参数的值为长类型 (long) -let options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' }; -console.log(new Intl.DateTimeFormat('de-DE', options).format(date)); +let options = { + weekday: "long", + year: "numeric", + month: "long", + day: "numeric", +}; +console.log(new Intl.DateTimeFormat("de-DE", options).format(date)); // "Donnerstag, 20. Dezember 2012" // 应用可能需要使用世界标准时间 (UTC),并且 UTC 使用短名字 (short) 展示 -options.timeZone = 'UTC'; -options.timeZoneName = 'short'; -console.log(new Intl.DateTimeFormat('en-US', options).format(date)); +options.timeZone = "UTC"; +options.timeZoneName = "short"; +console.log(new Intl.DateTimeFormat("en-US", options).format(date)); // "Thursday, December 20, 2012, GMT" // 有时需要更精确的选项 options = { - hour: 'numeric', minute: 'numeric', second: 'numeric', - timeZone: 'Australia/Sydney', - timeZoneName: 'short' + hour: "numeric", + minute: "numeric", + second: "numeric", + timeZone: "Australia/Sydney", + timeZoneName: "short", }; -console.log(new Intl.DateTimeFormat('en-AU', options).format(date)); +console.log(new Intl.DateTimeFormat("en-AU", options).format(date)); // "2:00:00 pm AEDT" // 再精确些... options.fractionalSecondDigits = 3; // 秒数的有效数字数量 -console.log(new Intl.DateTimeFormat('en-AU', options).format(date)); +console.log(new Intl.DateTimeFormat("en-AU", options).format(date)); // "2:00:00.200 pm AEDT" // 即便是美国,有时也需要使用 24 小时制 options = { - year: 'numeric', month: 'numeric', day: 'numeric', - hour: 'numeric', minute: 'numeric', second: 'numeric', + year: "numeric", + month: "numeric", + day: "numeric", + hour: "numeric", + minute: "numeric", + second: "numeric", hour12: false, - timeZone: 'America/Los_Angeles' + timeZone: "America/Los_Angeles", }; -console.log(new Intl.DateTimeFormat('en-US', options).format(date)); +console.log(new Intl.DateTimeFormat("en-US", options).format(date)); // "12/19/2012, 19:00:00" // 要使用选项,但是需要使用浏览器的默认区域,请使用 'default' -console.log(new Intl.DateTimeFormat('default', options).format(date)); +console.log(new Intl.DateTimeFormat("default", options).format(date)); // "12/19/2012, 19:00:00" // 有时需要包含一天的时段 -options = {hour: "numeric", dayPeriod: "short"}; -console.log(new Intl.DateTimeFormat('en-US', options).format(date)); +options = { hour: "numeric", dayPeriod: "short" }; +console.log(new Intl.DateTimeFormat("en-US", options).format(date)); // 10 at night ``` 使用的日历和数字格式也可以通过 `options` 参数分别设置: ```js -const options = {calendar: 'chinese', numberingSystem: 'arab'}; -const dateFormat = new Intl.DateTimeFormat('default', options); +const options = { calendar: "chinese", numberingSystem: "arab" }; +const dateFormat = new Intl.DateTimeFormat("default", options); const usedOptions = dateFormat.resolvedOptions(); console.log(usedOptions.calendar); // "chinese" diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/getcanonicallocales/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/getcanonicallocales/index.md index 734975e3ab8130..e222c088b77396 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/getcanonicallocales/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/getcanonicallocales/index.md @@ -27,10 +27,10 @@ Intl.getCanonicalLocales(locales) ## 示例 ```js -Intl.getCanonicalLocales('EN-US'); // ["en-US"] -Intl.getCanonicalLocales(['EN-US', 'Fr']); // ["en-US", "fr"] +Intl.getCanonicalLocales("EN-US"); // ["en-US"] +Intl.getCanonicalLocales(["EN-US", "Fr"]); // ["en-US", "fr"] -Intl.getCanonicalLocales('EN_US'); +Intl.getCanonicalLocales("EN_US"); // RangeError:'EN_US' is not a structurally valid language tag ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/listformat/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/listformat/index.md index 5d72d2988fe98f..380db49ba2db38 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/listformat/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/listformat/index.md @@ -49,15 +49,25 @@ new Intl.ListFormat([locales[, options]]) 下面的例子展示了用英语语言怎么去创建一个列表格式化器。 ```js -const list = ['Motorcycle', 'Bus', 'Car']; +const list = ["Motorcycle", "Bus", "Car"]; - console.log(new Intl.ListFormat('en-GB', { style: 'long', type: 'conjunction' }).format(list)); +console.log( + new Intl.ListFormat("en-GB", { style: "long", type: "conjunction" }).format( + list, + ), +); // > Motorcycle, Bus and Car - console.log(new Intl.ListFormat('en-GB', { style: 'short', type: 'disjunction' }).format(list)); +console.log( + new Intl.ListFormat("en-GB", { style: "short", type: "disjunction" }).format( + list, + ), +); // > Motorcycle, Bus or Car - console.log(new Intl.ListFormat('en-GB', { style: 'narrow', type: 'unit' }).format(list)); +console.log( + new Intl.ListFormat("en-GB", { style: "narrow", type: "unit" }).format(list), +); // > Motorcycle Bus Car ``` @@ -66,8 +76,13 @@ const list = ['Motorcycle', 'Bus', 'Car']; 下面的例子展示了如何创建一个返回被格式化部分的列表格式化器。 ```js -const list = ['Motorcycle', 'Bus', 'Car']; -console.log(new Intl.ListFormat('en-GB', { style: 'long', type: 'conjunction' }).formatToParts(list)); +const list = ["Motorcycle", "Bus", "Car"]; +console.log( + new Intl.ListFormat("en-GB", { + style: "long", + type: "conjunction", + }).formatToParts(list), +); // > [ { "type": "element", "value": "Motorcycle" }, { "type": "literal", "value": ", " }, { "type": "element", "value": "Bus" }, { "type": "literal", "value": ", and " }, { "type": "element", "value": "Car" } ]; ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/locale/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/locale/index.md index f20629760c261a..1e27cd82b4e324 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/locale/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/locale/index.md @@ -59,7 +59,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Intl/Locale 很简单,就是需要给{{jsxref("Locale/Locale", "Intl.Locale")}} 构造函数传入一个 locale 标识字符串作为参数: ```js -let us = new Intl.Locale('zh-Hans-CN'); +let us = new Intl.Locale("zh-Hans-CN"); ``` ### 使用配置实例化 @@ -67,7 +67,7 @@ let us = new Intl.Locale('zh-Hans-CN'); 构造函数支持传入 object 作为配置,object 中可包含多个配置属性。例如,设置 [`hourCycle`](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle) 属性,用于设置您所需要的小时周期类型: ```js -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/numberformat/format/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/numberformat/format/index.md index ace4ca5ee0cdc1..90d8d2392c231b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/numberformat/format/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/numberformat/format/index.md @@ -31,8 +31,8 @@ numberFormat.format(number) 使用 `format` 格式化一个单一的货币值,以俄罗斯为例: ```js -var options = { style: 'currency', currency: 'RUB' }; -var numberFormat = new Intl.NumberFormat('ru-RU', options); +var options = { style: "currency", currency: "RUB" }; +var numberFormat = new Intl.NumberFormat("ru-RU", options); console.log(numberFormat.format(654321.987)); // → "654 321,99 руб." ``` @@ -43,9 +43,9 @@ console.log(numberFormat.format(654321.987)); ```js var a = [123456.789, 987654.321, 456789.123]; -var numberFormat = new Intl.NumberFormat('es-ES'); +var numberFormat = new Intl.NumberFormat("es-ES"); var formatted = a.map(numberFormat.format); -console.log(formatted.join('; ')); +console.log(formatted.join("; ")); // → "123.456,789; 987.654,321; 456.789,123" ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/numberformat/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/numberformat/index.md index db095549549604..6f8a0d99b67785 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/numberformat/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/numberformat/index.md @@ -53,23 +53,23 @@ console.log(new Intl.NumberFormat().format(number)); const number = 123456.789; // 德语使用逗号(,)作为小数点,使用句号(.)作为千位分隔符 -console.log(new Intl.NumberFormat('de-DE').format(number)); +console.log(new Intl.NumberFormat("de-DE").format(number)); // → 123.456,789 // 大多数阿拉伯语国家使用阿拉伯语数字 -console.log(new Intl.NumberFormat('ar-EG').format(number)); +console.log(new Intl.NumberFormat("ar-EG").format(number)); // → ١٢٣٤٥٦٫٧٨٩ // India uses thousands/lakh/crore separators -console.log(new Intl.NumberFormat('en-IN').format(number)); +console.log(new Intl.NumberFormat("en-IN").format(number)); // → 1,23,456.789 // 通过编号系统中的 nu 扩展键请求,例如:中文十进制数字 -console.log(new Intl.NumberFormat('zh-Hans-CN-u-nu-hanidec').format(number)); +console.log(new Intl.NumberFormat("zh-Hans-CN-u-nu-hanidec").format(number)); // → 一二三,四五六.七八九 //当请求的语言不被支持,例如巴里,包含一个回滚语言印尼,这时候就会使用印尼语 -console.log(new Intl.NumberFormat(['ban', 'id']).format(number)); +console.log(new Intl.NumberFormat(["ban", "id"]).format(number)); // → 123.456,789 ``` @@ -81,29 +81,45 @@ console.log(new Intl.NumberFormat(['ban', 'id']).format(number)); const number = 123456.789; // 要求货币格式 -console.log(new Intl.NumberFormat('de-DE', { style: 'currency', currency: 'EUR' }).format(number)); +console.log( + new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format( + number, + ), +); // 123.456,79 € // 日元不使用小数位 -console.log(new Intl.NumberFormat('ja-JP', { style: 'currency', currency: 'JPY' }).format(number)); +console.log( + new Intl.NumberFormat("ja-JP", { style: "currency", currency: "JPY" }).format( + number, + ), +); // ¥123,457 // 限制三位有效数字 -console.log(new Intl.NumberFormat('en-IN', { maximumSignificantDigits: 3 }).format(number)); +console.log( + new Intl.NumberFormat("en-IN", { maximumSignificantDigits: 3 }).format( + number, + ), +); // 1,23,000 // 带有单位的格式化 -console.log(new Intl.NumberFormat('pt-PT', { - style: 'unit', - unit: 'kilometer-per-hour' -}).format(50)); +console.log( + new Intl.NumberFormat("pt-PT", { + style: "unit", + unit: "kilometer-per-hour", + }).format(50), +); // 50 km/h -console.log((16).toLocaleString('en-GB', { - style: 'unit', - unit: 'liter', - unitDisplay: 'long', -})); +console.log( + (16).toLocaleString("en-GB", { + style: "unit", + unit: "liter", + unitDisplay: "long", + }), +); // 16 litres ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/pluralrules/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/pluralrules/index.md index d246f5a1c0e35b..7d850983f483f1 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/pluralrules/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/pluralrules/index.md @@ -35,15 +35,15 @@ slug: Web/JavaScript/Reference/Global_Objects/Intl/PluralRules ```js // 阿拉伯语有不同的复数类别 -new Intl.PluralRules('ar-EG').select(0); +new Intl.PluralRules("ar-EG").select(0); // → 'zero' -new Intl.PluralRules('ar-EG').select(1); +new Intl.PluralRules("ar-EG").select(1); // → 'one' -new Intl.PluralRules('ar-EG').select(2); +new Intl.PluralRules("ar-EG").select(2); // → 'two' -new Intl.PluralRules('ar-EG').select(6); +new Intl.PluralRules("ar-EG").select(6); // → 'few' -new Intl.PluralRules('ar-EG').select(18); +new Intl.PluralRules("ar-EG").select(18); // → 'many' ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/relativetimeformat/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/relativetimeformat/index.md index deaacdaf5b8f9c..9e24c86c7e4cfc 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/relativetimeformat/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/relativetimeformat/index.md @@ -38,9 +38,9 @@ slug: Web/JavaScript/Reference/Global_Objects/Intl/RelativeTimeFormat // 在你的区域下创建相对时间格式化程序 // 显式传入默认值。 const rtf = new Intl.RelativeTimeFormat("en", { - localeMatcher: "bestfit",// 其他值:"lookup" - numeric: "always",// 其他值:"auto" - style: "long",// 其他值:"short"或"narrow" + localeMatcher: "bestfit", // 其他值:"lookup" + numeric: "always", // 其他值:"auto" + style: "long", // 其他值:"short"或"narrow" }); // 使用负值(-1)格式化相对时间。 @@ -55,13 +55,13 @@ rtf.format(1, "day"); // "in 1 day" 以下示例展示了如何创建一个用于返回格式化后的每一个部分的相对时间格式化程序。 ```js -const rtf = new Intl.RelativeTimeFormat("en",{numeric: "auto"}); +const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" }); // 使用日期单位格式化相对时间。 -rtf.formatToParts(-1,"day"); +rtf.formatToParts(-1, "day"); // [{type: "literal", value: "yesterday"}] -rtf.formatToParts(100,"day"); +rtf.formatToParts(100, "day"); // [ // { type: "literal", value: "in " }, // { type: "integer", value: "100", unit: "day" }, diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/segmenter/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/segmenter/index.md index 29e4f6eec38342..ac663acfad55eb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/segmenter/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/segmenter/index.md @@ -5,7 +5,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Intl/Segmenter {{JSRef}} - **`Intl.Segmenter`** 对象支持语言敏感的文本分割,允许你将一个字符串分割成有意义的片段(字、词、句)。 +**`Intl.Segmenter`** 对象支持语言敏感的文本分割,允许你将一个字符串分割成有意义的片段(字、词、句)。 {{EmbedInteractiveExample("pages/js/intl-segmenter.html")}} @@ -41,7 +41,7 @@ console.table(str.split(" ")); ```js example-good const str = "吾輩は猫である。名前はたぬき。"; -const segmenterJa = new Intl.Segmenter('ja-JP', { granularity: 'word' }); +const segmenterJa = new Intl.Segmenter("ja-JP", { granularity: "word" }); const segments = segmenterJa.segment(str); console.table(Array.from(segments)); diff --git a/files/zh-cn/web/javascript/reference/global_objects/intl/segmenter/segmenter/index.md b/files/zh-cn/web/javascript/reference/global_objects/intl/segmenter/segmenter/index.md index dd90f17dd46e66..ca4974f63d4f07 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/intl/segmenter/segmenter/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/intl/segmenter/segmenter/index.md @@ -52,8 +52,11 @@ new Intl.Segmenter(locales, options) ```js const text = "吾輩は猫である。名前はたぬき。"; -const japaneseSegmenter = new Intl.Segmenter("ja-JP", {granularity: "word"}); -console.log([...japaneseSegmenter.segment(text)].filter((segment) => segment.isWordLike).length); +const japaneseSegmenter = new Intl.Segmenter("ja-JP", { granularity: "word" }); +console.log( + [...japaneseSegmenter.segment(text)].filter((segment) => segment.isWordLike) + .length, +); // 8,文本将会分割为 '吾輩'|'は'|'猫'|'で'|'ある'|'。'|'名前'|'は'|'たぬき'|'。' ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/isfinite/index.md b/files/zh-cn/web/javascript/reference/global_objects/isfinite/index.md index c73de9c2efe80c..dbbed1523cbb4e 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/isfinite/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/isfinite/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/isFinite ## 语法 -```js +```js-nolint isFinite(testValue) ``` @@ -29,15 +29,14 @@ isFinite 是全局的方法,不与任何对象有关系。 ## 示例 ```js -isFinite(Infinity); // false -isFinite(NaN); // false +isFinite(Infinity); // false +isFinite(NaN); // false isFinite(-Infinity); // false -isFinite(0); // true -isFinite(2e64); // true,在更强壮的 Number.isFinite(null) 中将会得到 false - +isFinite(0); // true +isFinite(2e64); // true,在更强壮的 Number.isFinite(null) 中将会得到 false -isFinite("0"); // true,在更强壮的 Number.isFinite('0') 中将会得到 false +isFinite("0"); // true,在更强壮的 Number.isFinite('0') 中将会得到 false ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/isnan/index.md b/files/zh-cn/web/javascript/reference/global_objects/isnan/index.md index 66df1b3d2ec8e3..a8f6256f72fbc8 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/isnan/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/isnan/index.md @@ -45,37 +45,37 @@ isNaN(value) 一个`isNaN`的 polyfill 可以理解为(这个 polyfill 利用了`NaN`自身永不相等于自身这一特征): ```js -var isNaN = function(value) { - var n = Number(value); - return n !== n; +var isNaN = function (value) { + var n = Number(value); + return n !== n; }; ``` ## 示例 ```js -isNaN(NaN); // true +isNaN(NaN); // true isNaN(undefined); // true -isNaN({}); // true +isNaN({}); // true -isNaN(true); // false -isNaN(null); // false -isNaN(37); // false +isNaN(true); // false +isNaN(null); // false +isNaN(37); // false // strings -isNaN("37"); // false: 可以被转换成数值 37 -isNaN("37.37"); // false: 可以被转换成数值 37.37 -isNaN("37,5"); // true -isNaN('123ABC'); // true: parseInt("123ABC") 的结果是 123,但是 Number("123ABC") 结果是 NaN -isNaN(""); // false: 空字符串被转换成 0 -isNaN(" "); // false: 包含空格的字符串被转换成 0 +isNaN("37"); // false: 可以被转换成数值 37 +isNaN("37.37"); // false: 可以被转换成数值 37.37 +isNaN("37,5"); // true +isNaN("123ABC"); // true: parseInt("123ABC") 的结果是 123,但是 Number("123ABC") 结果是 NaN +isNaN(""); // false: 空字符串被转换成 0 +isNaN(" "); // false: 包含空格的字符串被转换成 0 // dates -isNaN(new Date()); // false -isNaN(new Date().toString()); // true +isNaN(new Date()); // false +isNaN(new Date().toString()); // true -isNaN("blabla") // true: "blabla"不能转换成数值 - // 转换成数值失败,返回 NaN +isNaN("blabla"); // true: "blabla"不能转换成数值 +// 转换成数值失败,返回 NaN ``` ### 有用的特殊行为 @@ -90,61 +90,61 @@ isNaN("blabla") // true: "blabla"不能转换成数值 function increment(x) { if (isNaN(x)) x = 0; return x + 1; -}; +} // The same effect with Number.isNaN(): function increment(x) { if (Number.isNaN(Number(x))) x = 0; return x + 1; -}; +} // In the following cases for the function's argument x, // isNaN(x) is always false, although x is indeed not a // number, but can be used as such in arithmetical // expressions -increment(""); // 1: "" is converted to 0 -increment(new String()); // 1: String object representing an empty string is converted to 0 -increment([]); // 1: [] is converted to 0 -increment(new Array()); // 1: Array object representing an empty array is converted to 0 -increment("0"); // 1: "0" is converted to 0 -increment("1"); // 2: "1" is converted to 1 -increment("0.1"); // 1.1: "0.1" is converted to 0.1 -increment("Infinity"); // Infinity: "Infinity" is converted to Infinity -increment(null); // 1: null is converted to 0 -increment(false); // 1: false is converted to 0 -increment(true); // 2: true is converted to 1 -increment(new Date()); // returns current date/time in milliseconds plus 1 +increment(""); // 1: "" is converted to 0 +increment(new String()); // 1: String object representing an empty string is converted to 0 +increment([]); // 1: [] is converted to 0 +increment(new Array()); // 1: Array object representing an empty array is converted to 0 +increment("0"); // 1: "0" is converted to 0 +increment("1"); // 2: "1" is converted to 1 +increment("0.1"); // 1.1: "0.1" is converted to 0.1 +increment("Infinity"); // Infinity: "Infinity" is converted to Infinity +increment(null); // 1: null is converted to 0 +increment(false); // 1: false is converted to 0 +increment(true); // 2: true is converted to 1 +increment(new Date()); // returns current date/time in milliseconds plus 1 // In the following cases for the function's argument x, // isNaN(x) is always false and x is indeed a number -increment(-1); // 0 -increment(-0.1); // 0.9 -increment(0); // 1 -increment(1); // 2 -increment(2); // 3 +increment(-1); // 0 +increment(-0.1); // 0.9 +increment(0); // 1 +increment(1); // 2 +increment(2); // 3 // ... and so on ... -increment(Infinity); // Infinity +increment(Infinity); // Infinity // In the following cases for the function's argument x, // isNaN(x) is always true and x is really not a number, // thus the function replaces it by 0 and returns 1 -increment(String); // 1 -increment(Array); // 1 -increment("blabla"); // 1 -increment("-blabla"); // 1 -increment(0/0); // 1 -increment("0/0"); // 1 -increment(Infinity/Infinity); // 1 -increment(NaN); // 1 -increment(undefined); // 1 -increment(); // 1 +increment(String); // 1 +increment(Array); // 1 +increment("blabla"); // 1 +increment("-blabla"); // 1 +increment(0 / 0); // 1 +increment("0/0"); // 1 +increment(Infinity / Infinity); // 1 +increment(NaN); // 1 +increment(undefined); // 1 +increment(); // 1 // isNaN(x) is always the same as isNaN(Number(x)), // but the presence of x is mandatory here! -isNaN(x) == isNaN(Number(x)) // true for every value of x, including x == undefined, - // because isNaN(undefined) == true and Number(undefined) returns NaN, - // but ... -isNaN() == isNaN(Number()) // false, because isNaN() == true and Number() == 0 +isNaN(x) == isNaN(Number(x)); // true for every value of x, including x == undefined, +// because isNaN(undefined) == true and Number(undefined) returns NaN, +// but ... +isNaN() == isNaN(Number()); // false, because isNaN() == true and Number() == 0 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/json/index.md b/files/zh-cn/web/javascript/reference/global_objects/json/index.md index 017faa84a68cc6..a077a2d6dee79f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/json/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/json/index.md @@ -117,40 +117,59 @@ ArrayElements = JSON ```js if (!window.JSON) { window.JSON = { - parse: function(sJSON) { return eval('(' + sJSON + ')'); }, + parse: function (sJSON) { + return eval("(" + sJSON + ")"); + }, stringify: (function () { var toString = Object.prototype.toString; - var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; }; - var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'}; - var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); }; + var isArray = + Array.isArray || + function (a) { + return toString.call(a) === "[object Array]"; + }; + var escMap = { + '"': '\\"', + "\\": "\\\\", + "\b": "\\b", + "\f": "\\f", + "\n": "\\n", + "\r": "\\r", + "\t": "\\t", + }; + var escFunc = function (m) { + return ( + escMap[m] || + "\\u" + (m.charCodeAt(0) + 0x10000).toString(16).substr(1) + ); + }; var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g; return function stringify(value) { if (value == null) { - return 'null'; - } else if (typeof value === 'number') { - return isFinite(value) ? value.toString() : 'null'; - } else if (typeof value === 'boolean') { + return "null"; + } else if (typeof value === "number") { + return isFinite(value) ? value.toString() : "null"; + } else if (typeof value === "boolean") { return value.toString(); - } else if (typeof value === 'object') { - if (typeof value.toJSON === 'function') { + } else if (typeof value === "object") { + if (typeof value.toJSON === "function") { return stringify(value.toJSON()); } else if (isArray(value)) { - var res = '['; + var res = "["; for (var i = 0; i < value.length; i++) - res += (i ? ', ' : '') + stringify(value[i]); - return res + ']'; - } else if (toString.call(value) === '[object Object]') { + res += (i ? ", " : "") + stringify(value[i]); + return res + "]"; + } else if (toString.call(value) === "[object Object]") { var tmp = []; for (var k in value) { if (value.hasOwnProperty(k)) - tmp.push(stringify(k) + ': ' + stringify(value[k])); + tmp.push(stringify(k) + ": " + stringify(value[k])); } - return '{' + tmp.join(', ') + '}'; + return "{" + tmp.join(", ") + "}"; } } return '"' + value.toString().replace(escRE, escFunc) + '"'; }; - })() + })(), }; } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/json/parse/index.md b/files/zh-cn/web/javascript/reference/global_objects/json/parse/index.md index 504bbe7903cc2e..e0deecf16f3422 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/json/parse/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/json/parse/index.md @@ -35,11 +35,11 @@ JSON.parse(text[, reviver]) ### 使用 `JSON.parse()` ```js -JSON.parse('{}'); // {} -JSON.parse('true'); // true -JSON.parse('"foo"'); // "foo" +JSON.parse("{}"); // {} +JSON.parse("true"); // true +JSON.parse('"foo"'); // "foo" JSON.parse('[1, 5, "false"]'); // [1, 5, "false"] -JSON.parse('null'); // null +JSON.parse("null"); // null ``` ### 使用 `reviver` 函数 @@ -50,14 +50,14 @@ JSON.parse('null'); // null ```js JSON.parse('{"p": 5}', function (k, v) { - if(k === '') return v; // 如果到了最顶层,则直接返回属性值, - return v * 2; // 否则将属性值变为原来的 2 倍。 -}); // { p: 10 } + if (k === "") return v; // 如果到了最顶层,则直接返回属性值, + return v * 2; // 否则将属性值变为原来的 2 倍。 +}); // { p: 10 } JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}', function (k, v) { - console.log(k); // 输出当前的属性名,从而得知遍历顺序是从内向外的, - // 最后一个属性名会是个空字符串。 - return v; // 返回原始属性值,相当于没有传递 reviver 参数。 + console.log(k); // 输出当前的属性名,从而得知遍历顺序是从内向外的, + // 最后一个属性名会是个空字符串。 + return v; // 返回原始属性值,相当于没有传递 reviver 参数。 }); // 1 @@ -82,100 +82,95 @@ JSON.parse('{"foo" : 1, }'); ```js // From https://github.com/douglascrockford/JSON-js/blob/master/json2.js if (typeof JSON.parse !== "function") { - var rx_one = /^[\],:{}\s]*$/; - var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; - var rx_three = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; - var rx_four = /(?:^|:|,)(?:\s*\[)+/g; - var rx_dangerous = /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; - JSON.parse = function(text, reviver) { - - // The parse method takes a text and an optional reviver function, and returns - // a JavaScript value if the text is a valid JSON text. - - var j; - - function walk(holder, key) { - - // The walk method is used to recursively walk the resulting structure so - // that modifications can be made. - - var k; - var v; - var value = holder[key]; - if (value && typeof value === "object") { - for (k in value) { - if (Object.prototype.hasOwnProperty.call(value, k)) { - v = walk(value, k); - if (v !== undefined) { - value[k] = v; - } else { - delete value[k]; - } - } - } + var rx_one = /^[\],:{}\s]*$/; + var rx_two = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g; + var rx_three = + /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g; + var rx_four = /(?:^|:|,)(?:\s*\[)+/g; + var rx_dangerous = + /[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; + JSON.parse = function (text, reviver) { + // The parse method takes a text and an optional reviver function, and returns + // a JavaScript value if the text is a valid JSON text. + + var j; + + function walk(holder, key) { + // The walk method is used to recursively walk the resulting structure so + // that modifications can be made. + + var k; + var v; + var value = holder[key]; + if (value && typeof value === "object") { + for (k in value) { + if (Object.prototype.hasOwnProperty.call(value, k)) { + v = walk(value, k); + if (v !== undefined) { + value[k] = v; + } else { + delete value[k]; } - return reviver.call(holder, key, value); + } } - - - // Parsing happens in four stages. In the first stage, we replace certain - // Unicode characters with escape sequences. JavaScript handles many characters - // incorrectly, either silently deleting them, or treating them as line endings. - - text = String(text); - rx_dangerous.lastIndex = 0; - if (rx_dangerous.test(text)) { - text = text.replace(rx_dangerous, function(a) { - return ( - "\\u" + - ("0000" + a.charCodeAt(0).toString(16)).slice(-4) - ); - }); - } - - // In the second stage, we run the text against regular expressions that look - // for non-JSON patterns. We are especially concerned with "()" and "new" - // because they can cause invocation, and "=" because it can cause mutation. - // But just to be safe, we want to reject all unexpected forms. - - // We split the second stage into 4 regexp operations in order to work around - // crippling inefficiencies in IE's and Safari's regexp engines. First we - // replace the JSON backslash pairs with "@" (a non-JSON character). Second, we - // replace all simple value tokens with "]" characters. Third, we delete all - // open brackets that follow a colon or comma or that begin the text. Finally, - // we look to see that the remaining characters are only whitespace or "]" or - // "," or ":" or "{" or "}". If that is so, then the text is safe for eval. - - if ( - rx_one.test( - text - .replace(rx_two, "@") - .replace(rx_three, "]") - .replace(rx_four, "") - ) - ) { - - // In the third stage we use the eval function to compile the text into a - // JavaScript structure. The "{" operator is subject to a syntactic ambiguity - // in JavaScript: it can begin a block or an object literal. We wrap the text - // in parens to eliminate the ambiguity. - - j = eval("(" + text + ")"); - - // In the optional fourth stage, we recursively walk the new structure, passing - // each name/value pair to a reviver function for possible transformation. - - return (typeof reviver === "function") ? - walk({ - "": j - }, "") : - j; - } - - // If the text is not JSON parseable, then a SyntaxError is thrown. - - throw new SyntaxError("JSON.parse"); - }; + } + return reviver.call(holder, key, value); + } + + // Parsing happens in four stages. In the first stage, we replace certain + // Unicode characters with escape sequences. JavaScript handles many characters + // incorrectly, either silently deleting them, or treating them as line endings. + + text = String(text); + rx_dangerous.lastIndex = 0; + if (rx_dangerous.test(text)) { + text = text.replace(rx_dangerous, function (a) { + return "\\u" + ("0000" + a.charCodeAt(0).toString(16)).slice(-4); + }); + } + + // In the second stage, we run the text against regular expressions that look + // for non-JSON patterns. We are especially concerned with "()" and "new" + // because they can cause invocation, and "=" because it can cause mutation. + // But just to be safe, we want to reject all unexpected forms. + + // We split the second stage into 4 regexp operations in order to work around + // crippling inefficiencies in IE's and Safari's regexp engines. First we + // replace the JSON backslash pairs with "@" (a non-JSON character). Second, we + // replace all simple value tokens with "]" characters. Third, we delete all + // open brackets that follow a colon or comma or that begin the text. Finally, + // we look to see that the remaining characters are only whitespace or "]" or + // "," or ":" or "{" or "}". If that is so, then the text is safe for eval. + + if ( + rx_one.test( + text.replace(rx_two, "@").replace(rx_three, "]").replace(rx_four, ""), + ) + ) { + // In the third stage we use the eval function to compile the text into a + // JavaScript structure. The "{" operator is subject to a syntactic ambiguity + // in JavaScript: it can begin a block or an object literal. We wrap the text + // in parens to eliminate the ambiguity. + + j = eval("(" + text + ")"); + + // In the optional fourth stage, we recursively walk the new structure, passing + // each name/value pair to a reviver function for possible transformation. + + return typeof reviver === "function" + ? walk( + { + "": j, + }, + "", + ) + : j; + } + + // If the text is not JSON parseable, then a SyntaxError is thrown. + + throw new SyntaxError("JSON.parse"); + }; } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/json/stringify/index.md b/files/zh-cn/web/javascript/reference/global_objects/json/stringify/index.md index 2b1a9be9954ab7..cdd3e1c6f0c607 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/json/stringify/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/json/stringify/index.md @@ -52,51 +52,44 @@ JSON.stringify(value[, replacer [, space]]) ### 使用 JSON.stringify ```js -JSON.stringify({}); // '{}' -JSON.stringify(true); // 'true' -JSON.stringify("foo"); // '"foo"' -JSON.stringify([1, "false", false]); // '[1,"false",false]' -JSON.stringify({ x: 5 }); // '{"x":5}' +JSON.stringify({}); // '{}' +JSON.stringify(true); // 'true' +JSON.stringify("foo"); // '"foo"' +JSON.stringify([1, "false", false]); // '[1,"false",false]' +JSON.stringify({ x: 5 }); // '{"x":5}' -JSON.stringify({x: 5, y: 6}); +JSON.stringify({ x: 5, y: 6 }); // "{"x":5,"y":6}" JSON.stringify([new Number(1), new String("false"), new Boolean(false)]); // '[1,"false",false]' -JSON.stringify({x: undefined, y: Object, z: Symbol("")}); +JSON.stringify({ x: undefined, y: Object, z: Symbol("") }); // '{}' JSON.stringify([undefined, Object, Symbol("")]); // '[null,null,null]' -JSON.stringify({[Symbol("foo")]: "foo"}); +JSON.stringify({ [Symbol("foo")]: "foo" }); // '{}' -JSON.stringify({[Symbol.for("foo")]: "foo"}, [Symbol.for("foo")]); +JSON.stringify({ [Symbol.for("foo")]: "foo" }, [Symbol.for("foo")]); // '{}' -JSON.stringify( - {[Symbol.for("foo")]: "foo"}, - function (k, v) { - if (typeof k === "symbol"){ - return "a symbol"; - } - } -); - +JSON.stringify({ [Symbol.for("foo")]: "foo" }, function (k, v) { + if (typeof k === "symbol") { + return "a symbol"; + } +}); // undefined // 不可枚举的属性默认会被忽略: JSON.stringify( - Object.create( - null, - { - x: { value: 'x', enumerable: false }, - y: { value: 'y', enumerable: true } - } - ) + Object.create(null, { + x: { value: "x", enumerable: false }, + y: { value: "y", enumerable: true }, + }), ); // "{"y":"y"}" @@ -148,13 +141,13 @@ JSON.stringify(foo, ['week', 'month']); `space` 参数用来控制结果字符串里面的间距。如果是一个数字,则在字符串化时每一级别会比上一级别缩进多这个数字值的空格(最多 10 个空格);如果是一个字符串,则每一级别会比上一级别多缩进该字符串(或该字符串的前 10 个字符)。 ```js -JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}' +JSON.stringify({ a: 2 }, null, " "); // '{\n "a": 2\n}' ``` 使用制表符(\t)来缩进: ```js -JSON.stringify({ uno: 1, dos : 2 }, null, '\t') +JSON.stringify({ uno: 1, dos: 2 }, null, "\t"); // '{ \ // "uno": 1, \ // "dos": 2 \ @@ -167,13 +160,13 @@ JSON.stringify({ uno: 1, dos : 2 }, null, '\t') ```js var obj = { - foo: 'foo', + foo: "foo", toJSON: function () { - return 'bar'; - } + return "bar"; + }, }; -JSON.stringify(obj); // '"bar"' -JSON.stringify({x: obj}); // '{"x":"bar"}' +JSON.stringify(obj); // '"bar"' +JSON.stringify({ x: obj }); // '{"x":"bar"}' ``` ### `JSON.stringify`用作 JavaScript @@ -212,22 +205,22 @@ alert(jsFriendlyJSONStringify(s)); // {"a":"\u2028","b":"\u2029"} ```js // 创建一个示例数据 var session = { - 'screens' : [], - 'state' : true + screens: [], + state: true, }; -session.screens.push({"name":"screenA", "width":450, "height":250}); -session.screens.push({"name":"screenB", "width":650, "height":350}); -session.screens.push({"name":"screenC", "width":750, "height":120}); -session.screens.push({"name":"screenD", "width":250, "height":60}); -session.screens.push({"name":"screenE", "width":390, "height":120}); -session.screens.push({"name":"screenF", "width":1240, "height":650}); +session.screens.push({ name: "screenA", width: 450, height: 250 }); +session.screens.push({ name: "screenB", width: 650, height: 350 }); +session.screens.push({ name: "screenC", width: 750, height: 120 }); +session.screens.push({ name: "screenD", width: 250, height: 60 }); +session.screens.push({ name: "screenE", width: 390, height: 120 }); +session.screens.push({ name: "screenF", width: 1240, height: 650 }); // 使用 JSON.stringify 转换为 JSON 字符串 // 然后使用 localStorage 保存在 session 名称里 -localStorage.setItem('session', JSON.stringify(session)); +localStorage.setItem("session", JSON.stringify(session)); // 然后是如何转换通过 JSON.stringify 生成的字符串,该字符串以 JSON 格式保存在 localStorage 里 -var restoredSession = JSON.parse(localStorage.getItem('session')); +var restoredSession = JSON.parse(localStorage.getItem("session")); // 现在 restoredSession 包含了保存在 localStorage 里的对象 console.log(restoredSession); diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/@@iterator/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/@@iterator/index.md index 7a1092fe150efe..a8c59616c914e2 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/@@iterator/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/@@iterator/index.md @@ -26,9 +26,9 @@ map 的 **iterator** 函数默认就是 {{jsxref("Map.prototype.entries()", "ent ```js var myMap = new Map(); -myMap.set('0', 'foo'); -myMap.set(1, 'bar'); -myMap.set({}, 'baz'); +myMap.set("0", "foo"); +myMap.set(1, "bar"); +myMap.set({}, "baz"); var mapIter = myMap[Symbol.iterator](); //返回的其实是个 generator @@ -41,9 +41,9 @@ console.log(mapIter.next().value); // [Object, "baz"] ```js var myMap = new Map(); -myMap.set('0', 'foo'); -myMap.set(1, 'bar'); -myMap.set({}, 'baz'); +myMap.set("0", "foo"); +myMap.set(1, "bar"); +myMap.set({}, "baz"); for (const entry of myMap) { console.log(entry); diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/@@species/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/@@species/index.md index 9841295ee5357d..fce4fbe7bbbf44 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/@@species/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/@@species/index.md @@ -31,7 +31,9 @@ In a derived collection object (e.g. your custom map `MyMap`), the `MyMap` speci ```js class MyMap extends Map { // 重写覆盖 MyMap species to the parent Map constructor - static get [Symbol.species]() { return Map; } + static get [Symbol.species]() { + return Map; + } } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/clear/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/clear/index.md index 6f2e37bbad05f1..00b6c053759d1b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/clear/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/clear/index.md @@ -25,16 +25,16 @@ clear() ```js const myMap = new Map(); -myMap.set('bar', 'baz'); -myMap.set(1, 'foo'); +myMap.set("bar", "baz"); +myMap.set(1, "foo"); -console.log(myMap.size); // 2 -console.log(myMap.has('bar')); // true +console.log(myMap.size); // 2 +console.log(myMap.has("bar")); // true myMap.clear(); -console.log(myMap.size); // 0 -console.log(myMap.has('bar')); // false +console.log(myMap.size); // 0 +console.log(myMap.has("bar")); // false ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/delete/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/delete/index.md index 43a1ea516542ee..41f80f7f429da9 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/delete/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/delete/index.md @@ -33,7 +33,7 @@ const myMap = new Map(); myMap.set("bar", "foo"); console.log(myMap.delete("bar")); // 返回 true。成功地移除元素 -console.log(myMap.has("bar")); // 返回 false。"bar" 元素将不再存在于 Map 实例中 +console.log(myMap.has("bar")); // 返回 false。"bar" 元素将不再存在于 Map 实例中 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.md index 4e7ef9517fbab0..b78630f8825705 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/foreach/index.md @@ -57,7 +57,11 @@ forEach(callbackFn, thisArg) function logMapElements(value, key, map) { console.log(`map.get('${key}') = ${value}`); } -new Map([['foo', 3], ['bar', {}], ['baz', undefined]]).forEach(logMapElements); +new Map([ + ["foo", 3], + ["bar", {}], + ["baz", undefined], +]).forEach(logMapElements); // logs: // "map.get('foo') = 3" // "map.get('bar') = [object Object]" diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/get/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/get/index.md index 34b94690a268c0..924c17848e0b4c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/get/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/get/index.md @@ -30,10 +30,10 @@ get(key) ```js const myMap = new Map(); -myMap.set('bar', 'foo'); +myMap.set("bar", "foo"); -console.log(myMap.get('bar')); // 返回 "foo" -console.log(myMap.get('baz')); // 返回 undefined +console.log(myMap.get("bar")); // 返回 "foo" +console.log(myMap.get("baz")); // 返回 undefined ``` ### 使用 get() 检索对对象的引用 @@ -41,12 +41,12 @@ console.log(myMap.get('baz')); // 返回 undefined ```js const arr = []; const myMap = new Map(); -myMap.set('bar', arr); +myMap.set("bar", arr); -myMap.get('bar').push('foo'); +myMap.get("bar").push("foo"); console.log(arr); // ["foo"] -console.log(myMap.get('bar')); // ["foo"] +console.log(myMap.get("bar")); // ["foo"] ``` 注意,持有原始对象引用的映射实际上意味着对象不能被垃圾回收,这可能会导致意外的内存问题。如果你希望存储在映射中的对象具有与原始对象相同的生命周期,请考虑使用 {{jsxref("WeakMap")}}。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/has/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/has/index.md index 18a226a69a4907..4444e09c10b043 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/has/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/has/index.md @@ -32,8 +32,8 @@ has(key) const myMap = new Map(); myMap.set("bar", "foo"); -console.log(myMap.has("bar")); // true -console.log(myMap.has("baz")); // false +console.log(myMap.has("bar")); // true +console.log(myMap.has("baz")); // false ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/index.md index 52301111b0b8af..97b0956ed213b0 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/index.md @@ -138,8 +138,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Map ```js example-bad const wrongMap = new Map(); -wrongMap['bla'] = 'blaa'; -wrongMap['bla2'] = 'blaaa2'; +wrongMap["bla"] = "blaa"; +wrongMap["bla2"] = "blaaa2"; console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' } ``` @@ -147,23 +147,23 @@ console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' } 但这种设置属性的方式不会改变 Map 的数据结构。它使用的是通用对象的特性。`'bla'` 的值未被存储在 Map 中,无法被查询到。其他的对这一数据的操作也会失败: ```js example-bad -wrongMap.has('bla') // false -wrongMap.delete('bla') // false -console.log(wrongMap) // Map { bla: 'blaa', bla2: 'blaaa2' } +wrongMap.has("bla"); // false +wrongMap.delete("bla"); // false +console.log(wrongMap); // Map { bla: 'blaa', bla2: 'blaaa2' } ``` 正确的存储数据到 Map 中的方式是使用 `set(key, value)` 方法。 ```js example-good -const contacts = new Map() -contacts.set('Jessie', {phone: "213-555-1234", address: "123 N 1st Ave"}) -contacts.has('Jessie') // true -contacts.get('Hilary') // undefined -contacts.set('Hilary', {phone: "617-555-4321", address: "321 S 2nd St"}) -contacts.get('Jessie') // {phone: "213-555-1234", address: "123 N 1st Ave"} -contacts.delete('Raymond') // false -contacts.delete('Jessie') // true -console.log(contacts.size) // 1 +const contacts = new Map(); +contacts.set("Jessie", { phone: "213-555-1234", address: "123 N 1st Ave" }); +contacts.has("Jessie"); // true +contacts.get("Hilary"); // undefined +contacts.set("Hilary", { phone: "617-555-4321", address: "321 S 2nd St" }); +contacts.get("Jessie"); // {phone: "213-555-1234", address: "123 N 1st Ave"} +contacts.delete("Raymond"); // false +contacts.delete("Jessie"); // true +console.log(contacts.size); // 1 ``` ## 构造函数 @@ -194,6 +194,7 @@ console.log(contacts.size) // 1 - {{jsxref("Map.prototype.set()")}} - : 在 `Map` 对象中设置与指定的键 `key` 关联的值,并返回 `Map` 对象。 - {{jsxref("Map.@@iterator", "Map.prototype[@@iterator]()")}} + - : 返回一个新的迭代对象,其为一个包含 `Map` 对象中所有键值对的 `[key, value]` 数组,并以插入 `Map` 对象的顺序排列。 - {{jsxref("Map.prototype.keys()")}} @@ -212,9 +213,9 @@ console.log(contacts.size) // 1 ```js const myMap = new Map(); -const keyString = 'a string'; +const keyString = "a string"; const keyObj = {}; -const keyFunc = function() {}; +const keyFunc = function () {}; // 添加键 myMap.set(keyString, "和键'a string'关联的值"); @@ -228,9 +229,9 @@ console.log(myMap.get(keyString)); // "和键'a string'关联的值" console.log(myMap.get(keyObj)); // "和键 keyObj 关联的值" console.log(myMap.get(keyFunc)); // "和键 keyFunc 关联的值" -console.log(myMap.get('a string')); // "和键'a string'关联的值",因为 keyString === 'a string' +console.log(myMap.get("a string")); // "和键'a string'关联的值",因为 keyString === 'a string' console.log(myMap.get({})); // undefined,因为 keyObj !== {} -console.log(myMap.get(function() {})); // undefined,因为 keyFunc !== function () {} +console.log(myMap.get(function () {})); // undefined,因为 keyFunc !== function () {} ``` ### 将 NaN 作为 Map 的键 @@ -239,12 +240,12 @@ console.log(myMap.get(function() {})); // undefined,因为 keyFunc !== functio ```js const myMap = new Map(); -myMap.set(NaN, 'not a number'); +myMap.set(NaN, "not a number"); myMap.get(NaN); // "not a number" -const otherNaN = Number('foo'); +const otherNaN = Number("foo"); myMap.get(otherNaN); // "not a number" ``` @@ -255,8 +256,8 @@ myMap.get(otherNaN); ```js const myMap = new Map(); -myMap.set(0, 'zero'); -myMap.set(1, 'one'); +myMap.set(0, "zero"); +myMap.set(1, "one"); for (const [key, value] of myMap) { console.log(`${key} = ${value}`); @@ -298,12 +299,15 @@ myMap.forEach((value, key) => { ### Map 与数组的关系 ```js -const kvArray = [['key1', 'value1'], ['key2', 'value2']]; +const kvArray = [ + ["key1", "value1"], + ["key2", "value2"], +]; // 使用常规的 Map 构造函数可以将一个二维键值对数组转换成一个 Map 对象 const myMap = new Map(kvArray); -console.log(myMap.get('key1')); // "value1" +console.log(myMap.get("key1")); // "value1" // 使用 Array.from 函数可以将一个 Map 对象转换成一个二维键值对数组 console.log(Array.from(myMap)); // 输出和 kvArray 相同的数组 @@ -320,9 +324,7 @@ console.log(Array.from(myMap.keys())); // 输出 ["key1", "key2"] `Map` 能像数组一样被复制: ```js -const original = new Map([ - [1, 'one'], -]); +const original = new Map([[1, "one"]]); const clone = new Map(original); @@ -336,14 +338,14 @@ console.log(original === clone); // false. 浅比较 不为同一个对象的引 ```js const first = new Map([ - [1, 'one'], - [2, 'two'], - [3, 'three'], + [1, "one"], + [2, "two"], + [3, "three"], ]); const second = new Map([ - [1, 'uno'], - [2, 'dos'] + [1, "uno"], + [2, "dos"], ]); // 合并两个 Map 对象时,如果有重复的键值,则后面的会覆盖前面的。 @@ -359,18 +361,18 @@ console.log(merged.get(3)); // three ```js const first = new Map([ - [1, 'one'], - [2, 'two'], - [3, 'three'], + [1, "one"], + [2, "two"], + [3, "three"], ]); const second = new Map([ - [1, 'uno'], - [2, 'dos'] + [1, "uno"], + [2, "dos"], ]); // Map 对象同数组进行合并时,如果有重复的键值,则后面的会覆盖前面的。 -const merged = new Map([...first, ...second, [1, 'eins']]); +const merged = new Map([...first, ...second, [1, "eins"]]); console.log(merged.get(1)); // eins console.log(merged.get(2)); // dos diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/map/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/map/index.md index 7be843617255ce..b8650c70ffad08 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/map/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/map/index.md @@ -27,9 +27,9 @@ new Map(iterable) ```js const myMap = new Map([ - [1, 'one'], - [2, 'two'], - [3, 'three'], + [1, "one"], + [2, "two"], + [3, "three"], ]); ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/set/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/set/index.md index 46c5c409546d9c..da4e5d4eec70cb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/set/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/set/index.md @@ -34,11 +34,11 @@ set(key, value) const myMap = new Map(); // 将一个新元素添加到 Map 对象 -myMap.set('bar', 'foo'); -myMap.set(1, 'foobar'); +myMap.set("bar", "foo"); +myMap.set(1, "foobar"); // 在 Map 对象中更新某个元素的值 -myMap.set('bar', 'baz'); +myMap.set("bar", "baz"); ``` ### 链式使用 set() @@ -47,9 +47,7 @@ myMap.set('bar', 'baz'); ```js // 链式调用添加元素 -myMap.set('bar', 'foo') - .set(1, 'foobar') - .set(2, 'baz'); +myMap.set("bar", "foo").set(1, "foobar").set(2, "baz"); ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/size/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/size/index.md index 4013ee3e803b34..42513100c974e5 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/size/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/size/index.md @@ -19,9 +19,9 @@ slug: Web/JavaScript/Reference/Global_Objects/Map/size ```js const myMap = new Map(); -myMap.set('a', 'alpha'); -myMap.set('b', 'beta'); -myMap.set('g', 'gamma'); +myMap.set("a", "alpha"); +myMap.set("b", "beta"); +myMap.set("g", "gamma"); console.log(myMap.size); // 3 ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/map/values/index.md b/files/zh-cn/web/javascript/reference/global_objects/map/values/index.md index 45b0ee6fd0721b..db30f81c9df44a 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/map/values/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/map/values/index.md @@ -25,9 +25,9 @@ values() ```js const myMap = new Map(); -myMap.set('0', 'foo'); -myMap.set(1, 'bar'); -myMap.set({}, 'baz'); +myMap.set("0", "foo"); +myMap.set(1, "bar"); +myMap.set({}, "baz"); const mapIter = myMap.values(); diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/acos/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/acos/index.md index 4086ccdb14697f..84ae253948d988 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/acos/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/acos/index.md @@ -33,12 +33,12 @@ Math.acos(x) ### 示例:使用 `Math.acos` ```js -Math.acos(-2); // NaN -Math.acos(-1); // 3.141592653589793 -Math.acos(0); // 1.5707963267948966 +Math.acos(-2); // NaN +Math.acos(-1); // 3.141592653589793 +Math.acos(0); // 1.5707963267948966 Math.acos(0.5); // 1.0471975511965979 -Math.acos(1); // 0 -Math.acos(2); // NaN +Math.acos(1); // 0 +Math.acos(2); // NaN ``` 对于小于 -1 或大于 1 的值,`Math.acos` 返回 `NaN`。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/acosh/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/acosh/index.md index 17f77e57e5edb6..b9efec00499d77 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/acosh/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/acosh/index.md @@ -36,11 +36,11 @@ Math.acosh(x) ### 使用 `Math.acosh()` ```js -Math.acosh(-1); // NaN -Math.acosh(0); // NaN +Math.acosh(-1); // NaN +Math.acosh(0); // NaN Math.acosh(0.5); // NaN -Math.acosh(1); // 0 -Math.acosh(2); // 1.3169578969248166 +Math.acosh(1); // 0 +Math.acosh(2); // 1.3169578969248166 ``` 当参数小于 1 时,`Math.acosh()` 将返回 {{jsxref("NaN")}}。 @@ -50,9 +50,11 @@ Math.acosh(2); // 1.3169578969248166 当 x1x \geq 1 时,都有 arcosh(x)=ln(x+x2-1)\operatorname {arcosh} (x) = \ln \left(x + \sqrt{x^{2} - 1} \right) ,因此可以使用以下函数实现: ```js -Math.acosh = Math.acosh || function(x) { - return Math.log(x + Math.sqrt(x * x - 1)); -}; +Math.acosh = + Math.acosh || + function (x) { + return Math.log(x + Math.sqrt(x * x - 1)); + }; ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/asin/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/asin/index.md index 9b4debe5329ff6..77984461808291 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/asin/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/asin/index.md @@ -33,12 +33,12 @@ Math.asin(x) ### 示例:使用 `Math.asin()` ```js -Math.asin(-2); // NaN -Math.asin(-1); // -1.5707963267948966 (-pi/2) -Math.asin(0); // 0 +Math.asin(-2); // NaN +Math.asin(-1); // -1.5707963267948966 (-pi/2) +Math.asin(0); // 0 Math.asin(0.5); // 0.5235987755982989 -Math.asin(1); // 1.5707963267948966 (pi/2) -Math.asin(2); // NaN +Math.asin(1); // 1.5707963267948966 (pi/2) +Math.asin(2); // NaN ``` 对于小于 -1 或大于 1 的参数值,`Math.asin` 返回 `NaN`。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/asinh/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/asinh/index.md index 08980d11a5bfb2..7c48fcf80c2bc5 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/asinh/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/asinh/index.md @@ -35,8 +35,8 @@ Math.asinh(x) ### 使用 `Math.asinh()` ```js -Math.asinh(1); // 0.881373587019543 -Math.asinh(0); // 0 +Math.asinh(1); // 0.881373587019543 +Math.asinh(0); // 0 ``` ## Polyfill @@ -44,13 +44,15 @@ Math.asinh(0); // 0 As a quick and dirty hack the expression arsinh(x)=ln(x+x2+1)\operatorname {arsinh} (x) = \ln \left(x + \sqrt{x^{2} + 1} \right) may be used directly for a coarse emulation by the following function: ```js -Math.asinh = Math.asinh || function(x) { - if (x === -Infinity) { - return x; - } else { - return Math.log(x + Math.sqrt(x * x + 1)); - } -}; +Math.asinh = + Math.asinh || + function (x) { + if (x === -Infinity) { + return x; + } else { + return Math.log(x + Math.sqrt(x * x + 1)); + } + }; ``` Been formally correct it suffers from a number of issues related to floating point computations. Accurate result requires special handling of positive/negative, small/large arguments as it done e.g. in [glibc](https://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/dbl-64/s_asinh.c) or [GNU Scientific Library](http://git.savannah.gnu.org/cgit/gsl.git/tree/sys/invhyp.c). diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/atan/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/atan/index.md index 0a6c0114509bef..92d94f0cd695ae 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/atan/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/atan/index.md @@ -33,8 +33,8 @@ Math.atan(x) ### 示例:使用 `Math.atan` ```js -Math.atan(1); // 0.7853981633974483 -Math.atan(0); // 0 +Math.atan(1); // 0.7853981633974483 +Math.atan(0); // 0 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/atanh/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/atanh/index.md index acc7af8c39ce27..bedf650d350351 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/atanh/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/atanh/index.md @@ -26,15 +26,15 @@ Math.atanh(x) ## 示例 -### `使用 Math.atanh()` +### 使用 `Math.atanh()` ```js -Math.atanh(-2); // NaN -Math.atanh(-1); // -Infinity -Math.atanh(0); // 0 +Math.atanh(-2); // NaN +Math.atanh(-1); // -Infinity +Math.atanh(0); // 0 Math.atanh(0.5); // 0.5493061443340548 -Math.atanh(1); // Infinity -Math.atanh(2); // NaN +Math.atanh(1); // Infinity +Math.atanh(2); // NaN ``` 对于大于 1 或是小于-1 的值,函数返回 {{jsxref("NaN")}} 。 @@ -44,9 +44,11 @@ Math.atanh(2); // NaN For \left|x\right| < 1, we have \operatorname {artanh} (x) = \frac{1}{2}\ln \left( \frac{1 + x}{1 - x} \right) so this can be emulated by the following function: ```js -Math.atanh = Math.atanh || function(x) { - return Math.log((1+x)/(1-x)) / 2; -}; +Math.atanh = + Math.atanh || + function (x) { + return Math.log((1 + x) / (1 - x)) / 2; + }; ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/cbrt/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/cbrt/index.md index 5815d5680871fb..439bb8d3dfb245 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/cbrt/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/cbrt/index.md @@ -45,7 +45,7 @@ Math.cbrt(0); // 0 Math.cbrt(1); // 1 Math.cbrt(Infinity); // Infinity Math.cbrt(null); // 0 -Math.cbrt(2); // 1.2599210498948732 +Math.cbrt(2); // 1.2599210498948732 ``` ## Polyfill @@ -54,8 +54,8 @@ Math.cbrt(2); // 1.2599210498948732 ```js if (!Math.cbrt) { - Math.cbrt = function(x) { - var y = Math.pow(Math.abs(x), 1/3); + Math.cbrt = function (x) { + var y = Math.pow(Math.abs(x), 1 / 3); return x < 0 ? -y : y; }; } diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/clz32/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/clz32/index.md index 34a15b05a03fca..1b27759c7f9965 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/clz32/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/clz32/index.md @@ -35,14 +35,14 @@ Math.clz32 (x) ## 示例 ```js -Math.clz32(1) // 31 -Math.clz32(1000) // 22 -Math.clz32() // 32 +Math.clz32(1); // 31 +Math.clz32(1000); // 22 +Math.clz32(); // 32 [NaN, Infinity, -Infinity, 0, -0, null, undefined, "foo", {}, []].filter(function (n) { return Math.clz32(n) !== 32 -}) // [] -Math.clz32(true) // 31 -Math.clz32(3.5) // 30 +}); // [] +Math.clz32(true); // 31 +Math.clz32(3.5); // 30 ``` ## 计算前导 1 的个数 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/cos/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/cos/index.md index 7c79dbdf543a07..7d826eb528f55f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/cos/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/cos/index.md @@ -31,10 +31,10 @@ Math.cos(x) ### 示例:使用 `Math.cos` ```js -Math.cos(0); // 1 -Math.cos(1); // 0.5403023058681398 +Math.cos(0); // 1 +Math.cos(1); // 0.5403023058681398 -Math.cos(Math.PI); // -1 +Math.cos(Math.PI); // -1 Math.cos(2 * Math.PI); // 1 ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/cosh/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/cosh/index.md index 817bc14951cc98..019a0476afaebb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/cosh/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/cosh/index.md @@ -29,8 +29,8 @@ Math.cosh(x) ### 使用 `Math.cosh()` ```js -Math.cosh(0); // 1 -Math.cosh(1); // 1.5430806348152437 +Math.cosh(0); // 1 +Math.cosh(1); // 1.5430806348152437 Math.cosh(-1); // 1.5430806348152437 ``` @@ -39,18 +39,22 @@ Math.cosh(-1); // 1.5430806348152437 可通过 {{jsxref("Math.exp()")}} 函数模拟实现: ```js -Math.cosh = Math.cosh || function(x) { - return (Math.exp(x) + Math.exp(-x)) / 2; -} +Math.cosh = + Math.cosh || + function (x) { + return (Math.exp(x) + Math.exp(-x)) / 2; + }; ``` 或只调用一次 {{jsxref("Math.exp()")}} 函数: ```js -Math.cosh = Math.cosh || function(x) { - var y = Math.exp(x); - return (y + 1 / y) / 2; -}; +Math.cosh = + Math.cosh || + function (x) { + var y = Math.exp(x); + return (y + 1 / y) / 2; + }; ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/e/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/e/index.md index 61b057301c1470..7f29421e7489fa 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/e/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/e/index.md @@ -25,10 +25,10 @@ slug: Web/JavaScript/Reference/Global_Objects/Math/E ```js function getNapier() { - return Math.E + return Math.E; } -getNapier() // 2.718281828459045 +getNapier(); // 2.718281828459045 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/exp/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/exp/index.md index c68c3433573e64..050d1e4ab4e4b0 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/exp/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/exp/index.md @@ -30,8 +30,8 @@ Math.exp(x) ```js Math.exp(-1); // 0.36787944117144233 -Math.exp(0); // 1 -Math.exp(1); // 2.718281828459045 +Math.exp(0); // 1 +Math.exp(1); // 2.718281828459045 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/expm1/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/expm1/index.md index d8d40695a74d6b..3063eb47a0b9f4 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/expm1/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/expm1/index.md @@ -42,9 +42,11 @@ Math.expm1(Infinity); // Infinity 因为我们已经有了 `Math.exp` 函数,所以很容易 polyfill。 ```js -Math.expm1 = Math.expm1 || function (x) { - return Math.exp(x) - 1 -} +Math.expm1 = + Math.expm1 || + function (x) { + return Math.exp(x) - 1; + }; ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/floor/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/floor/index.md index 22894f2604ffc5..22263993112eda 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/floor/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/floor/index.md @@ -63,7 +63,7 @@ function decimalAdjust(type, value, exp) { type = String(type); if (!["round", "floor", "ceil"].includes(type)) { throw new TypeError( - "The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'." + "The type of decimal adjustment must be one of 'round', 'floor', or 'ceil'.", ); } exp = Number(exp); diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/fround/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/fround/index.md index 0f7e8fa410d704..144276f061e444 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/fround/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/fround/index.md @@ -11,7 +11,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Math/fround ## 语法 -```js +```js-nolint Math.fround(doubleFloat) ``` @@ -60,20 +60,20 @@ Math.fround(2 ** 150); // Infinity 如果参数无法转换成数字,或者为 {{jsxref("NaN")}}(`NaN`),`Math.fround()` 会返回 `NaN`: ```js -Math.fround('abc'); // NaN +Math.fround("abc"); // NaN Math.fround(NaN); // NaN ``` 在某些精度不高的场合下,可以通过将二个浮点数转换成 32 位浮点数进行比较,以解决 64 位浮点数比较结果不正确的问题: ```js -0.1 + 0.2 == 0.3; //false +0.1 + 0.2 == 0.3; //false function equal(v1, v2) { - return Math.fround(v1) == Math.fround(v2); + return Math.fround(v1) == Math.fround(v2); } -equal(0.1 + 0.2, 0.3); //true +equal(0.1 + 0.2, 0.3); //true ``` ## Polyfill @@ -81,11 +81,13 @@ equal(0.1 + 0.2, 0.3); //true 下面的函数可以模拟这个 API,前提是浏览器必须已经支持 {{jsxref("Float32Array")}}: ```js -Math.fround = Math.fround || (function (array) { - return function(x) { - return array[0] = x, array[0]; - }; -})(new Float32Array(1)); +Math.fround = + Math.fround || + (function (array) { + return function (x) { + return (array[0] = x), array[0]; + }; + })(new Float32Array(1)); ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/hypot/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/hypot/index.md index d38b7324179da8..e84b5852cbda88 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/hypot/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/hypot/index.md @@ -47,13 +47,13 @@ Math.hypot([value1[,value2, ...]]) ### Using `Math.hypot()` ```js -Math.hypot(3, 4); // 5 -Math.hypot(3, 4, 5); // 7.0710678118654755 -Math.hypot(); // 0 -Math.hypot(NaN); // NaN -Math.hypot(3, 4, 'foo'); // NaN, +'foo' => NaN -Math.hypot(3, 4, '5'); // 7.0710678118654755, +'5' => 5 -Math.hypot(-3); // 3, the same as Math.abs(-3) +Math.hypot(3, 4); // 5 +Math.hypot(3, 4, 5); // 7.0710678118654755 +Math.hypot(); // 0 +Math.hypot(NaN); // NaN +Math.hypot(3, 4, "foo"); // NaN, +'foo' => NaN +Math.hypot(3, 4, "5"); // 7.0710678118654755, +'5' => 5 +Math.hypot(-3); // 3, the same as Math.abs(-3) ``` ## 向下兼容 @@ -61,30 +61,33 @@ Math.hypot(-3); // 3, the same as Math.abs(-3) 此函数可以使用如下代码模拟: ```js -if (!Math.hypot) Math.hypot = function() { - var y = 0, i = arguments.length; - while (i--) y += arguments[i] * arguments[i]; - return Math.sqrt(y); -}; +if (!Math.hypot) + Math.hypot = function () { + var y = 0, + i = arguments.length; + while (i--) y += arguments[i] * arguments[i]; + return Math.sqrt(y); + }; ``` 另一种避免结果溢出的实现: ```js -if (!Math.hypot) Math.hypot = function (x, y) { - // https://bugzilla.mozilla.org/show_bug.cgi?id=896264#c28 - var max = 0; - var s = 0; - for (var i = 0; i < arguments.length; i += 1) { - var arg = Math.abs(Number(arguments[i])); - if (arg > max) { - s *= (max / arg) * (max / arg); - max = arg; +if (!Math.hypot) + Math.hypot = function (x, y) { + // https://bugzilla.mozilla.org/show_bug.cgi?id=896264#c28 + var max = 0; + var s = 0; + for (var i = 0; i < arguments.length; i += 1) { + var arg = Math.abs(Number(arguments[i])); + if (arg > max) { + s *= (max / arg) * (max / arg); + max = arg; + } + s += arg === 0 && max === 0 ? 0 : (arg / max) * (arg / max); } - s += arg === 0 && max === 0 ? 0 : (arg / max) * (arg / max); - } - return max === 1 / 0 ? 1 / 0 : max * Math.sqrt(s); -}; + return max === 1 / 0 ? 1 / 0 : max * Math.sqrt(s); + }; ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/imul/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/imul/index.md index 7b08d0fe0ee968..1bb6b5a602e742 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/imul/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/imul/index.md @@ -31,11 +31,11 @@ var product = Math.imul(a, b) ## 示例 ```js -Math.imul(2, 4) // 8 -Math.imul(-1, 8) // -8 -Math.imul(-2, -2) // 4 -Math.imul(0xffffffff, 5) //-5 -Math.imul(0xfffffffe, 5) //-10 +Math.imul(2, 4); // 8 +Math.imul(-1, 8); // -8 +Math.imul(-2, -2); // 4 +Math.imul(0xffffffff, 5); //-5 +Math.imul(0xfffffffe, 5); //-10 ``` ## Polyfill @@ -43,33 +43,35 @@ Math.imul(0xfffffffe, 5) //-10 下面的 JavaScript 代码可以实现该函数: ```js -if (!Math.imul) Math.imul = function(a, b) { - var aHi = (a >>> 16) & 0xffff; - var aLo = a & 0xffff; - var bHi = (b >>> 16) & 0xffff; - var bLo = b & 0xffff; - // the shift by 0 fixes the sign on the high part - // the final |0 converts the unsigned value into a signed value - return ((aLo * bLo) + (((aHi * bLo + aLo * bHi) << 16) >>> 0) | 0); -}; +if (!Math.imul) + Math.imul = function (a, b) { + var aHi = (a >>> 16) & 0xffff; + var aLo = a & 0xffff; + var bHi = (b >>> 16) & 0xffff; + var bLo = b & 0xffff; + // the shift by 0 fixes the sign on the high part + // the final |0 converts the unsigned value into a signed value + return (aLo * bLo + (((aHi * bLo + aLo * bHi) << 16) >>> 0)) | 0; + }; ``` 然而,下面的实现性能会更好一些。因为运行这段 polyfill 的浏览器很有可能会在内部使用浮点数,而不是整数表示 javascript 的 Number。 ```js -if (!Math.imul) Math.imul = function(opA, opB) { - opB |= 0; // ensure that opB is an integer. opA will automatically be coerced. - // floating points give us 53 bits of precision to work with plus 1 sign bit - // automatically handled for our convienence: - // 1. 0x003fffff /*opA & 0x000fffff*/ * 0x7fffffff /*opB*/ = 0x1fffff7fc00001 - // 0x1fffff7fc00001 < Number.MAX_SAFE_INTEGER /*0x1fffffffffffff*/ - var result = (opA & 0x003fffff) * opB; - // 2. We can remove an integer coersion from the statement above because: - // 0x1fffff7fc00001 + 0xffc00000 = 0x1fffffff800001 - // 0x1fffffff800001 < Number.MAX_SAFE_INTEGER /*0x1fffffffffffff*/ - if (opA & 0xffc00000 /*!== 0*/) result += (opA & 0xffc00000) * opB |0; - return result |0; -}; +if (!Math.imul) + Math.imul = function (opA, opB) { + opB |= 0; // ensure that opB is an integer. opA will automatically be coerced. + // floating points give us 53 bits of precision to work with plus 1 sign bit + // automatically handled for our convienence: + // 1. 0x003fffff /*opA & 0x000fffff*/ * 0x7fffffff /*opB*/ = 0x1fffff7fc00001 + // 0x1fffff7fc00001 < Number.MAX_SAFE_INTEGER /*0x1fffffffffffff*/ + var result = (opA & 0x003fffff) * opB; + // 2. We can remove an integer coersion from the statement above because: + // 0x1fffff7fc00001 + 0xffc00000 = 0x1fffffff800001 + // 0x1fffffff800001 < Number.MAX_SAFE_INTEGER /*0x1fffffffffffff*/ + if (opA & 0xffc00000 /*!== 0*/) result += ((opA & 0xffc00000) * opB) | 0; + return result | 0; + }; ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/ln10/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/ln10/index.md index bd4233fdab756b..71d512347666dc 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/ln10/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/ln10/index.md @@ -25,10 +25,10 @@ slug: Web/JavaScript/Reference/Global_Objects/Math/LN10 ```js function getNatLog10() { - return Math.LN10 + return Math.LN10; } -getNatLog10() // 2.302585092994046 +getNatLog10(); // 2.302585092994046 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/ln2/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/ln2/index.md index 0c93d7f8973a62..c1e3f8b10d6d68 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/ln2/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/ln2/index.md @@ -25,10 +25,10 @@ slug: Web/JavaScript/Reference/Global_Objects/Math/LN2 ```js function getNatLog2() { - return Math.LN2 + return Math.LN2; } -getNatLog2() // 0.6931471805599453 +getNatLog2(); // 0.6931471805599453 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/log/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/log/index.md index bc51cd13283849..c8aa3d0dd12d45 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/log/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/log/index.md @@ -47,7 +47,7 @@ Math.log(10); // 2.302585092994046 ```js function getBaseLog(x, y) { - return Math.log(y) / Math.log(x); + return Math.log(y) / Math.log(x); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/log10/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/log10/index.md index 2718f2d0dfe919..5e3eeb8c2846e9 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/log10/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/log10/index.md @@ -27,13 +27,13 @@ Math.log10(x) ## 示例 ```js -Math.log10(10) // 1 -Math.log10(100) // 2 -Math.log10("100")// 2 -Math.log10(1) // 0 -Math.log10(0) // -Infinity -Math.log10(-2) // NaN -Math.log10("foo")// NaN +Math.log10(10); // 1 +Math.log10(100); // 2 +Math.log10("100"); // 2 +Math.log10(1); // 0 +Math.log10(0); // -Infinity +Math.log10(-2); // NaN +Math.log10("foo"); // NaN ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/log10e/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/log10e/index.md index ee3704d929a9b6..aa9b6e42084bd2 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/log10e/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/log10e/index.md @@ -25,10 +25,10 @@ slug: Web/JavaScript/Reference/Global_Objects/Math/LOG10E ```js function getLog10e() { - return Math.LOG10E + return Math.LOG10E; } -getLog10e() // 0.4342944819032518 +getLog10e(); // 0.4342944819032518 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/log1p/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/log1p/index.md index 47e52587789ae2..725855d112b81c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/log1p/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/log1p/index.md @@ -31,12 +31,12 @@ Math.log1p(x) **示例** ```js -Math.log1p(Math.E-1) // 1 -Math.log1p(0) // 0 -Math.log1p("0") // 0 -Math.log1p(-1) // -Infinity -Math.log1p(-2) // NaN -Math.log1p("foo") // NaN +Math.log1p(Math.E - 1); // 1 +Math.log1p(0); // 0 +Math.log1p("0"); // 0 +Math.log1p(-1); // -Infinity +Math.log1p(-2); // NaN +Math.log1p("foo"); // NaN ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/log2/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/log2/index.md index c7f5ac53b5f1e7..436c9be1758730 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/log2/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/log2/index.md @@ -27,13 +27,13 @@ Math.log2(x) ## 示例 ```js -Math.log2(2) // 1 -Math.log2(1024) // 10 -Math.log2(1) // 0 -Math.log2(0) // -Infinity -Math.log2(-2) // NaN -Math.log2("1024")// 10 -Math.log2("foo") // NaN +Math.log2(2); // 1 +Math.log2(1024); // 10 +Math.log2(1); // 0 +Math.log2(0); // -Infinity +Math.log2(-2); // NaN +Math.log2("1024"); // 10 +Math.log2("foo"); // NaN ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/log2e/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/log2e/index.md index 50d8353e05b618..6aa418d4a57309 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/log2e/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/log2e/index.md @@ -25,10 +25,10 @@ slug: Web/JavaScript/Reference/Global_Objects/Math/LOG2E ```js function getLog2e() { - return Math.LOG2E + return Math.LOG2E; } -getLog2e() // 1.4426950408889634 +getLog2e(); // 1.4426950408889634 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/pi/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/pi/index.md index 0e0f81fe7e8c70..c375362fbbf975 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/pi/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/pi/index.md @@ -24,11 +24,11 @@ slug: Web/JavaScript/Reference/Global_Objects/Math/PI 下面的函数使用 Math.PI 计算给定半径的圆周长: ```js -function calculateCircumference (radius) { +function calculateCircumference(radius) { return 2 * Math.PI * radius; } -calculateCircumference(1); // 6.283185307179586 +calculateCircumference(1); // 6.283185307179586 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/pow/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/pow/index.md index 7d7a5d5fe2b038..969dde09de8c44 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/pow/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/pow/index.md @@ -31,8 +31,8 @@ Math.pow(base, exponent) ### 使用 `Math.pow` ```js -function raisePower(x,y) { - return Math.pow(x,y) +function raisePower(x, y) { + return Math.pow(x, y); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/round/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/round/index.md index e8509c2390c4fb..9d9997c4094235 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/round/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/round/index.md @@ -31,18 +31,17 @@ Math.round(x) ## 示例 ```js -x = Math.round(20.49); //20 -x = Math.round(20.5); //21 -x = Math.round(-20.5); //-20 -x = Math.round(-20.51); //-21 +x = Math.round(20.49); //20 +x = Math.round(20.5); //21 +x = Math.round(-20.5); //-20 +x = Math.round(-20.51); //-21 ``` ### 小数舍入 ```js // 闭包 -(function(){ - +(function () { /** * Decimal adjustment of a number. * @@ -53,42 +52,41 @@ x = Math.round(-20.51); //-21 */ function decimalAdjust(type, value, exp) { // If the exp is undefined or zero... - if (typeof exp === 'undefined' || +exp === 0) { + if (typeof exp === "undefined" || +exp === 0) { return Math[type](value); } value = +value; exp = +exp; // If the value is not a number or the exp is not an integer... - if (isNaN(value) || !(typeof exp === 'number' && exp % 1 === 0)) { + if (isNaN(value) || !(typeof exp === "number" && exp % 1 === 0)) { return NaN; } // Shift - value = value.toString().split('e'); - value = Math[type](+(value[0] + 'e' + (value[1] ? (+value[1] - exp) : -exp))); + value = value.toString().split("e"); + value = Math[type](+(value[0] + "e" + (value[1] ? +value[1] - exp : -exp))); // Shift back - value = value.toString().split('e'); - return +(value[0] + 'e' + (value[1] ? (+value[1] + exp) : exp)); + value = value.toString().split("e"); + return +(value[0] + "e" + (value[1] ? +value[1] + exp : exp)); } // Decimal round if (!Math.round10) { - Math.round10 = function(value, exp) { - return decimalAdjust('round', value, exp); + Math.round10 = function (value, exp) { + return decimalAdjust("round", value, exp); }; } // Decimal floor if (!Math.floor10) { - Math.floor10 = function(value, exp) { - return decimalAdjust('floor', value, exp); + Math.floor10 = function (value, exp) { + return decimalAdjust("floor", value, exp); }; } // Decimal ceil if (!Math.ceil10) { - Math.ceil10 = function(value, exp) { - return decimalAdjust('ceil', value, exp); + Math.ceil10 = function (value, exp) { + return decimalAdjust("ceil", value, exp); }; } - })(); // Round @@ -117,12 +115,12 @@ Math.ceil10(-59, 1); // -50 ```js function round(number, precision) { - return Math.round(+number + 'e' + precision) / Math.pow(10, precision); - //same as: - //return Number(Math.round(+number + 'e' + precision) + 'e-' + precision); + return Math.round(+number + "e" + precision) / Math.pow(10, precision); + //same as: + //return Number(Math.round(+number + 'e' + precision) + 'e-' + precision); } -round(1.005, 2); //1.01 +round(1.005, 2); //1.01 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/sign/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/sign/index.md index 4b069a156c69e7..c2b058f9c29460 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/sign/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/sign/index.md @@ -33,24 +33,23 @@ Math.sign(x); ### 使用 Math.sign() ```js -Math.sign(3); // 1 -Math.sign(-3); // -1 -Math.sign("-3"); // -1 -Math.sign(0); // 0 -Math.sign(-0); // -0 -Math.sign(NaN); // NaN +Math.sign(3); // 1 +Math.sign(-3); // -1 +Math.sign("-3"); // -1 +Math.sign(0); // 0 +Math.sign(-0); // -0 +Math.sign(NaN); // NaN Math.sign("foo"); // NaN -Math.sign(); // NaN +Math.sign(); // NaN ``` ## Polyfill ```js function sign(x) { - x = +x ;// convert to a number - if (x === 0 || isNaN(x)) - return x; - return x > 0 ? 1 : -1; + x = +x; // convert to a number + if (x === 0 || isNaN(x)) return x; + return x > 0 ? 1 : -1; } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/sin/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/sin/index.md index b101d181fa63b3..1a05d02c9abff6 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/sin/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/sin/index.md @@ -31,8 +31,8 @@ Math.sin(x) ### 示例:使用 `Math.sin` ```js -Math.sin(0); // 0 -Math.sin(1); // 0.8414709848078965 +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.md b/files/zh-cn/web/javascript/reference/global_objects/math/sinh/index.md index e123bc3ef7131f..ca9c3823379209 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/sinh/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/sinh/index.md @@ -29,10 +29,10 @@ Math.sinh(x) ## 示例 ```js -Math.sinh(0) // 0 -Math.sinh(1) // 1.1752011936438014 -Math.sinh("-1") // -1.1752011936438014 -Math.sinh("foo") // NaN +Math.sinh(0); // 0 +Math.sinh(1); // 1.1752011936438014 +Math.sinh("-1"); // -1.1752011936438014 +Math.sinh("foo"); // NaN ``` ## 规范 @@ -44,8 +44,8 @@ Math.sinh("foo") // NaN 该函数可以使用 {{jsxref("Math.exp()")}} 函数来实现: ```js -function sinh(x){ - return (Math.exp(x) - Math.exp(-x)) / 2; +function sinh(x) { + return (Math.exp(x) - Math.exp(-x)) / 2; } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/sqrt1_2/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/sqrt1_2/index.md index a7fbdcfb04aea4..23d7b4de445a2e 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/sqrt1_2/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/sqrt1_2/index.md @@ -25,10 +25,10 @@ slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT1_2 ```js function getRoot1_2() { - return Math.SQRT1_2 + return Math.SQRT1_2; } -getRoot1_2() // 0.7071067811865476 +getRoot1_2(); // 0.7071067811865476 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/sqrt2/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/sqrt2/index.md index 499323c61cfc50..1924603f01f32f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/sqrt2/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/sqrt2/index.md @@ -21,7 +21,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Math/SQRT2 ```js function getRoot2() { - return Math.SQRT2; + return Math.SQRT2; } getRoot2(); // 1.4142135623730951 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/tan/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/tan/index.md index b9ceddd367453e..4bcc69bf2f4332 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/tan/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/tan/index.md @@ -34,7 +34,7 @@ Math.tan(x) ```js function getTan(x) { - return Math.tan(x); + return Math.tan(x); } ``` @@ -42,8 +42,8 @@ function getTan(x) { ```js function getTanDeg(deg) { - var rad = deg * Math.PI/180; - return Math.tan(rad); + var rad = (deg * Math.PI) / 180; + return Math.tan(rad); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/tanh/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/tanh/index.md index e9285bb64c9158..0a3b4992ae2ffa 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/tanh/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/tanh/index.md @@ -35,9 +35,9 @@ Math.tanh(x) ### 使用 `Math.tanh()` ```js -Math.tanh(0); // 0 +Math.tanh(0); // 0 Math.tanh(Infinity); // 1 -Math.tanh(1); // 0.7615941559557649 +Math.tanh(1); // 0.7615941559557649 ``` ## 向下兼容 @@ -45,10 +45,13 @@ Math.tanh(1); // 0.7615941559557649 `tanh()` 可以通过 {{jsxref("Math.exp()")}} 函数实现: ```js -Math.tanh = Math.tanh || function(x){ - var a = Math.exp(+x), b = Math.exp(-x); +Math.tanh = + Math.tanh || + function (x) { + var a = Math.exp(+x), + b = Math.exp(-x); return a == Infinity ? 1 : b == Infinity ? -1 : (a - b) / (a + b); -} + }; ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/math/trunc/index.md b/files/zh-cn/web/javascript/reference/global_objects/math/trunc/index.md index 43f86491095331..d3292ea21f0864 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/math/trunc/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/math/trunc/index.md @@ -33,14 +33,14 @@ Math.trunc(value) ## 示例 ```js -Math.trunc(13.37) // 13 -Math.trunc(42.84) // 42 -Math.trunc(0.123) // 0 -Math.trunc(-0.123) // -0 -Math.trunc("-1.123") // -1 -Math.trunc(NaN) // NaN -Math.trunc("foo") // NaN -Math.trunc() // NaN +Math.trunc(13.37); // 13 +Math.trunc(42.84); // 42 +Math.trunc(0.123); // 0 +Math.trunc(-0.123); // -0 +Math.trunc("-1.123"); // -1 +Math.trunc(NaN); // NaN +Math.trunc("foo"); // NaN +Math.trunc(); // NaN ``` ## Polyfill diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/epsilon/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/epsilon/index.md index 20aacb3b62a490..8e9bdc66196b9b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/epsilon/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/epsilon/index.md @@ -23,7 +23,7 @@ slug: Web/JavaScript/Reference/Global_Objects/Number/EPSILON x = 0.2; y = 0.3; z = 0.1; -equal = (Math.abs(x - y + z) < Number.EPSILON); +equal = Math.abs(x - y + z) < Number.EPSILON; ``` ## Polyfill diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/isfinite/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/isfinite/index.md index 5e3d366a852961..2974a952070093 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/isfinite/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/isfinite/index.md @@ -31,25 +31,26 @@ Number.isFinite(value) ## Polyfill ```js -if (Number.isFinite === undefined) Number.isFinite = function(value) { - return typeof value === 'number' && isFinite(value); -} +if (Number.isFinite === undefined) + Number.isFinite = function (value) { + return typeof value === "number" && isFinite(value); + }; ``` ## 示例 ```js -Number.isFinite(Infinity); // false -Number.isFinite(NaN); // false +Number.isFinite(Infinity); // false +Number.isFinite(NaN); // false Number.isFinite(-Infinity); // false -Number.isFinite(0); // true -Number.isFinite(2e64); // true +Number.isFinite(0); // true +Number.isFinite(2e64); // true -Number.isFinite('0'); // false, would've been true with - // global isFinite('0') -Number.isFinite(null); // false, would've been true with - // global isFinite(null) +Number.isFinite("0"); // false, would've been true with +// global isFinite('0') +Number.isFinite(null); // false, would've been true with +// global isFinite(null) ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/isinteger/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/isinteger/index.md index 26142b105598e5..d1ece267378493 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/isinteger/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/isinteger/index.md @@ -31,29 +31,33 @@ Number.isInteger(value) ## 示例 ```js -Number.isInteger(0); // true -Number.isInteger(1); // true -Number.isInteger(-100000); // true +Number.isInteger(0); // true +Number.isInteger(1); // true +Number.isInteger(-100000); // true -Number.isInteger(0.1); // false -Number.isInteger(Math.PI); // false +Number.isInteger(0.1); // false +Number.isInteger(Math.PI); // false -Number.isInteger(Infinity); // false +Number.isInteger(Infinity); // false Number.isInteger(-Infinity); // false -Number.isInteger("10"); // false -Number.isInteger(true); // false -Number.isInteger(false); // false -Number.isInteger([1]); // false +Number.isInteger("10"); // false +Number.isInteger(true); // false +Number.isInteger(false); // false +Number.isInteger([1]); // false ``` ## Polyfill ```js -Number.isInteger = Number.isInteger || function(value) { - return typeof value === "number" && - isFinite(value) && - Math.floor(value) === value; -}; +Number.isInteger = + Number.isInteger || + function (value) { + return ( + typeof value === "number" && + isFinite(value) && + Math.floor(value) === value + ); + }; ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/isnan/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/isnan/index.md index 8872731f779628..1ca94453e68c2c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/isnan/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/isnan/index.md @@ -33,15 +33,15 @@ Number.isNaN(value) ## 示例 ```js -Number.isNaN(NaN); // true +Number.isNaN(NaN); // true Number.isNaN(Number.NaN); // true -Number.isNaN(0 / 0) // true +Number.isNaN(0 / 0); // true // 下面这几个如果使用全局的 isNaN() 时,会返回 true。 -Number.isNaN("NaN"); // false,字符串 "NaN" 不会被隐式转换成数字 NaN。 -Number.isNaN(undefined); // false -Number.isNaN({}); // false -Number.isNaN("blabla"); // false +Number.isNaN("NaN"); // false,字符串 "NaN" 不会被隐式转换成数字 NaN。 +Number.isNaN(undefined); // false +Number.isNaN({}); // false +Number.isNaN("blabla"); // false // 下面的都返回 false Number.isNaN(true); @@ -56,9 +56,11 @@ Number.isNaN(" "); ## Polyfill ```js -Number.isNaN = Number.isNaN || function(value) { +Number.isNaN = + Number.isNaN || + function (value) { return typeof value === "number" && isNaN(value); -} + }; ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/issafeinteger/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/issafeinteger/index.md index c6711f347fdfdf..08596b698e5e9b 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/issafeinteger/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/issafeinteger/index.md @@ -34,14 +34,14 @@ Number.isSafeInteger(testValue) ## 示例 ```js -Number.isSafeInteger(3); // true -Number.isSafeInteger(Math.pow(2, 53)) // false -Number.isSafeInteger(Math.pow(2, 53) - 1) // true -Number.isSafeInteger(NaN); // false -Number.isSafeInteger(Infinity); // false -Number.isSafeInteger("3"); // false -Number.isSafeInteger(3.1); // false -Number.isSafeInteger(3.0); // true +Number.isSafeInteger(3); // true +Number.isSafeInteger(Math.pow(2, 53)); // false +Number.isSafeInteger(Math.pow(2, 53) - 1); // true +Number.isSafeInteger(NaN); // false +Number.isSafeInteger(Infinity); // false +Number.isSafeInteger("3"); // false +Number.isSafeInteger(3.1); // false +Number.isSafeInteger(3.0); // true ``` ## Polyfill diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/max_safe_integer/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/max_safe_integer/index.md index e7aac25df61415..31fdb607ede02c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/max_safe_integer/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/max_safe_integer/index.md @@ -20,8 +20,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER ## 示例 ```js -Number.MAX_SAFE_INTEGER // 9007199254740991 -Math.pow(2, 53) - 1 // 9007199254740991 +Number.MAX_SAFE_INTEGER; // 9007199254740991 +Math.pow(2, 53) - 1; // 9007199254740991 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/max_value/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/max_value/index.md index bb773b132b1ad3..d9ea2c1de2dfdb 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/max_value/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/max_value/index.md @@ -25,9 +25,9 @@ slug: Web/JavaScript/Reference/Global_Objects/Number/MAX_VALUE ```js if (num1 * num2 <= Number.MAX_VALUE) { - func1(); + func1(); } else { - func2(); + func2(); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/min_safe_integer/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/min_safe_integer/index.md index fd07912115f573..f38cc46cad164f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/min_safe_integer/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/min_safe_integer/index.md @@ -18,8 +18,8 @@ slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_SAFE_INTEGER ## 示例 ```js -Number.MIN_SAFE_INTEGER // -9007199254740991 --(Math.pow(2, 53) - 1) // -9007199254740991 +Number.MIN_SAFE_INTEGER; // -9007199254740991 +-(Math.pow(2, 53) - 1); // -9007199254740991 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/min_value/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/min_value/index.md index e37b9f5a056fa4..2df4badabe21f7 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/min_value/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/min_value/index.md @@ -27,9 +27,9 @@ slug: Web/JavaScript/Reference/Global_Objects/Number/MIN_VALUE ```js if (num1 / num2 >= Number.MIN_VALUE) { - func1(); + func1(); } else { - func2(); + func2(); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/negative_infinity/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/negative_infinity/index.md index 79b41a87180b75..9094e97bc9ccd2 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/negative_infinity/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/negative_infinity/index.md @@ -35,10 +35,10 @@ slug: Web/JavaScript/Reference/Global_Objects/Number/NEGATIVE_INFINITY 下例中,赋值给变量 `smallNumber` 一个明显小于 JavaScript 中的最小值的值。当 `if` 语句执行时,`smallNumber` 值为 "`-Infinity`",因此在继续执行代码前,`smallNumber` 被设为一个更容易管理的值。 ```js -var smallNumber = (-Number.MAX_VALUE) * 2 +var smallNumber = -Number.MAX_VALUE * 2; if (smallNumber == Number.NEGATIVE_INFINITY) { - smallNumber = returnFinite(); + smallNumber = returnFinite(); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/number/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/number/index.md index d3688b484bb971..22776fde48c869 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/number/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/number/index.md @@ -34,12 +34,12 @@ Number(value) ### 创建 Number 对象 ```js -const a = new Number('123'); // a === 123 为 false -const b = Number('123'); // b === 123 为 true -a instanceof Number; // 为 true -b instanceof Number; // 为 false -typeof a // "object" -typeof b // "number" +const a = new Number("123"); // a === 123 为 false +const b = Number("123"); // b === 123 为 true +a instanceof Number; // 为 true +b instanceof Number; // 为 false +typeof a; // "object" +typeof b; // "number" ``` ### 使用 Number() 将 BigInt 转换为数值 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/parseint/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/parseint/index.md index d6fa5b3afbbf60..d7117fdf376e10 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/parseint/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/parseint/index.md @@ -36,7 +36,7 @@ Number.parseInt(string, radix) 这个方法和全局的 {{jsxref("parseInt", "parseInt()")}} 函数具有一样的函数功能: ```js -Number.parseInt === parseInt // true +Number.parseInt === parseInt; // true ``` 其目的是对全局变量进行模块化,另见 {{jsxref("parseInt", "parseInt()")}} 获取更多详情和示例。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/positive_infinity/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/positive_infinity/index.md index f0a2d9d194edf9..5da6487fceba54 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/positive_infinity/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/positive_infinity/index.md @@ -35,9 +35,9 @@ You might use the `Number.POSITIVE_INFINITY` property to indicate an error condi 下例中,赋值给变量 `bigNumber` 一个大于 JavaScript 中最大值的值。当 `if` 语句执行时,变量 `bigNumber` 值为 "`Infinity`",因此在继续执行代码前,为变量 `bigNumber` 设置一个容易管理的值。 ```js -var bigNumber = Number.MAX_VALUE * 2 +var bigNumber = Number.MAX_VALUE * 2; if (bigNumber == Number.POSITIVE_INFINITY) { - bigNumber = returnFinite(); + bigNumber = returnFinite(); } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/toexponential/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/toexponential/index.md index 868d437709fe52..5068535c4deb48 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/toexponential/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/toexponential/index.md @@ -46,9 +46,9 @@ alert("numObj.toExponential(4) is " + numObj.toExponential(4)); //输出 7.7123e alert("numObj.toExponential(2) is " + numObj.toExponential(2)); //输出 7.71e+1 -alert("77.1234.toExponential() is " + 77.1234.toExponential()); //输出 7.71234e+1 +alert("77.1234.toExponential() is " + (77.1234).toExponential()); //输出 7.71234e+1 -alert("77 .toExponential() is " + 77 .toExponential()); //输出 7.7e+1 +alert("77 .toExponential() is " + (77).toExponential()); //输出 7.7e+1 ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/tofixed/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/tofixed/index.md index dffad0c1782f6e..2635a784b365ed 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/tofixed/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/tofixed/index.md @@ -44,24 +44,23 @@ numObj.toFixed(digits) ```js var numObj = 12345.6789; -numObj.toFixed(); // 返回 "12346":进行四舍六入五看情况,不包括小数部分 -numObj.toFixed(1); // 返回 "12345.7":进行四舍六入五看情况 +numObj.toFixed(); // 返回 "12346":进行四舍六入五看情况,不包括小数部分 +numObj.toFixed(1); // 返回 "12345.7":进行四舍六入五看情况 -numObj.toFixed(6); // 返回 "12345.678900":用 0 填充 +numObj.toFixed(6); // 返回 "12345.678900":用 0 填充 -(1.23e+20).toFixed(2); // 返回 "123000000000000000000.00" +(1.23e20).toFixed(2); // 返回 "123000000000000000000.00" -(1.23e-10).toFixed(2); // 返回 "0.00" +(1.23e-10).toFixed(2); // 返回 "0.00" -2.34.toFixed(1); // 返回 "2.3" +(2.34).toFixed(1); // 返回 "2.3" -2.35.toFixed(1) // 返回 '2.4'. Note it rounds up +(2.35).toFixed(1); // 返回 '2.4'. Note it rounds up -2.55.toFixed(1) // 返回 '2.5'. Note it rounds down - see warning above +(2.55).toFixed(1) - // 返回 '2.5'. Note it rounds down - see warning above + (2.34).toFixed(1); // 返回 -2.3(由于操作符优先级,负数不会返回字符串) --2.34.toFixed(1); // 返回 -2.3(由于操作符优先级,负数不会返回字符串) - -(-2.34).toFixed(1); // 返回 "-2.3"(若用括号提高优先级,则返回字符串) +(-2.34).toFixed(1); // 返回 "-2.3"(若用括号提高优先级,则返回字符串) ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/tolocalestring/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/tolocalestring/index.md index 8aa18722157c4b..c220712757d61e 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/tolocalestring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/tolocalestring/index.md @@ -67,9 +67,9 @@ console.log(number.toLocaleString()); // Displays "3,500" if in U.S. English loc function toLocaleStringSupportsLocales() { const number = 0; try { - number.toLocaleString('i'); + number.toLocaleString("i"); } catch (e) { - return e.name === 'RangeError'; + return e.name === "RangeError"; } return false; } @@ -79,7 +79,11 @@ function toLocaleStringSupportsLocales() { ```js function toLocaleStringSupportsOptions() { - return !!(typeof Intl === 'object' && Intl && typeof Intl.NumberFormat === 'function'); + return !!( + typeof Intl === "object" && + Intl && + typeof Intl.NumberFormat === "function" + ); } ``` @@ -93,23 +97,23 @@ function toLocaleStringSupportsOptions() { const number = 123456.789; // 德国使用逗号作为小数分隔符,分位周期为千位 -console.log(number.toLocaleString('de-DE')); +console.log(number.toLocaleString("de-DE")); // → 123.456,789 // 在大多数阿拉伯语国家使用阿拉伯语数字 -console.log(number.toLocaleString('ar-EG')); +console.log(number.toLocaleString("ar-EG")); // → ١٢٣٤٥٦٫٧٨٩ // 印度使用千位/拉克(十万)/克若尔(千万)分隔 -console.log(number.toLocaleString('en-IN')); +console.log(number.toLocaleString("en-IN")); // → 1,23,456.789 // nu 扩展字段要求编号系统,e.g. 中文十进制 -console.log(number.toLocaleString('zh-Hans-CN-u-nu-hanidec')); +console.log(number.toLocaleString("zh-Hans-CN-u-nu-hanidec")); // → 一二三,四五六.七八九 // 当请求不支持的语言时,例如巴厘语,加入一个备用语言,比如印尼语 -console.log(number.toLocaleString(['ban', 'id'])); +console.log(number.toLocaleString(["ban", "id"])); // → 123.456,789 ``` @@ -121,20 +125,29 @@ console.log(number.toLocaleString(['ban', 'id'])); const number = 123456.789; // 要求货币格式 -console.log(number.toLocaleString('de-DE', { style: 'currency', currency: 'EUR' })); +console.log( + number.toLocaleString("de-DE", { style: "currency", currency: "EUR" }), +); // → 123.456,79 € // 日元不使用小数位 -console.log(number.toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' })) +console.log( + number.toLocaleString("ja-JP", { style: "currency", currency: "JPY" }), +); // → ¥123,457 // 限制三位有效数字 -console.log(number.toLocaleString('en-IN', { maximumSignificantDigits: 3 })); +console.log(number.toLocaleString("en-IN", { maximumSignificantDigits: 3 })); // → 1,23,000 // 使用带选项的主机默认语言进行数字格式化 const num = 30000.65; -console.log(num.toLocaleString(undefined, {minimumFractionDigits: 2, maximumFractionDigits: 2})); +console.log( + num.toLocaleString(undefined, { + minimumFractionDigits: 2, + maximumFractionDigits: 2, + }), +); // → "30,000.65" 英语为默认语言 // → "30.000,65" 德语为默认语言 // → "30 000,65" 法语为默认语言 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/toprecision/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/toprecision/index.md index 1c87649ba8de12..01416872eba79c 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/toprecision/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/toprecision/index.md @@ -34,22 +34,22 @@ numObj.toPrecision(precision) ## 示例 ```js -let numObj = 5.123456 +let numObj = 5.123456; -console.log(numObj.toPrecision()) // 输出 '5.123456' -console.log(numObj.toPrecision(5)) // 输出 '5.1235' -console.log(numObj.toPrecision(2)) // 输出 '5.1' -console.log(numObj.toPrecision(1)) // 输出 '5' +console.log(numObj.toPrecision()); // 输出 '5.123456' +console.log(numObj.toPrecision(5)); // 输出 '5.1235' +console.log(numObj.toPrecision(2)); // 输出 '5.1' +console.log(numObj.toPrecision(1)); // 输出 '5' -numObj = 0.000123 +numObj = 0.000123; -console.log(numObj.toPrecision()) // 输出 '0.000123' -console.log(numObj.toPrecision(5)) // 输出 '0.00012300' -console.log(numObj.toPrecision(2)) // 输出 '0.00012' -console.log(numObj.toPrecision(1)) // 输出 '0.0001' +console.log(numObj.toPrecision()); // 输出 '0.000123' +console.log(numObj.toPrecision(5)); // 输出 '0.00012300' +console.log(numObj.toPrecision(2)); // 输出 '0.00012' +console.log(numObj.toPrecision(1)); // 输出 '0.0001' // 请注意,在某些情况下可能会返回科学计数法字符串 -console.log((1234.5).toPrecision(2)) // 输出 '1.2e+3' +console.log((1234.5).toPrecision(2)); // 输出 '1.2e+3' ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/tostring/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/tostring/index.md index c5beb5719f31ab..fdd242a2e732c8 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/tostring/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/tostring/index.md @@ -40,16 +40,16 @@ numObj.toString([radix]) ```js var count = 10; -console.log(count.toString()); // 输出 '10' -console.log((17).toString()); // 输出 '17' -console.log((17.2).toString()); // 输出 '17.2' +console.log(count.toString()); // 输出 '10' +console.log((17).toString()); // 输出 '17' +console.log((17.2).toString()); // 输出 '17.2' var x = 6; -console.log(x.toString(2)); // 输出 '110' -console.log((254).toString(16)); // 输出 'fe' +console.log(x.toString(2)); // 输出 '110' +console.log((254).toString(16)); // 输出 'fe' -console.log((-10).toString(2)); // 输出 '-1010' +console.log((-10).toString(2)); // 输出 '-1010' console.log((-0xff).toString(2)); // 输出 '-11111111' ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/number/valueof/index.md b/files/zh-cn/web/javascript/reference/global_objects/number/valueof/index.md index 051c83c9333bfc..669db4c252d804 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/number/valueof/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/number/valueof/index.md @@ -30,8 +30,8 @@ var numObj = new Number(10); console.log(typeof numObj); // object var num = numObj.valueOf(); -console.log(num); // 10 -console.log(typeof num); // number +console.log(num); // 10 +console.log(typeof num); // number ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/assign/index.md b/files/zh-cn/web/javascript/reference/global_objects/object/assign/index.md index 68c1e4d8870e1a..2c6091446d4e3f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/assign/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/object/assign/index.md @@ -90,7 +90,7 @@ const o3 = { c: 3 }; const obj = Object.assign(o1, o2, o3); console.log(obj); // { a: 1, b: 2, c: 3 } -console.log(o1); // { a: 1, b: 2, c: 3 },目标对象本身发生了变化 +console.log(o1); // { a: 1, b: 2, c: 3 },目标对象本身发生了变化 ``` ### 合并具有相同属性的对象 @@ -110,7 +110,7 @@ console.log(obj); // { a: 1, b: 2, c: 3 } ```js const o1 = { a: 1 }; -const o2 = { [Symbol('foo')]: 2 }; +const o2 = { [Symbol("foo")]: 2 }; const obj = Object.assign({}, o1, o2); console.log(obj); // { a : 1, [Symbol("foo")]: 2 } (cf. bug 1207182 on Firefox) @@ -141,10 +141,10 @@ console.log(copy); // { baz: 3 } ### 基本类型会被封装为对象 ```js -const v1 = 'abc'; +const v1 = "abc"; const v2 = true; const v3 = 10; -const v4 = Symbol('foo'); +const v4 = Symbol("foo"); const obj = Object.assign({}, v1, null, v2, undefined, v3, v4); // 基本类型将被封装,null 和 undefined 将被忽略。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/defineproperty/index.md b/files/zh-cn/web/javascript/reference/global_objects/object/defineproperty/index.md index f9fdac57c2c443..977db765ce8703 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/defineproperty/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/object/defineproperty/index.md @@ -188,7 +188,7 @@ console.log(o.a); // 37;赋值不会成功 writable: false, }); o.b = 3; // 抛出 TypeError: "b" is read-only - return o.b; // 如果没有上一行的话,会返回 2 + return o.b; // 如果没有上一行的话,会返回 2 })(); ``` @@ -209,7 +209,7 @@ Object.defineProperty(o, "b", { Object.defineProperty(o, "c", { value: 3, }); // enumerable 默认为 false -o.d = 4; // 通过赋值创建属性时 enumerable 默认为 true +o.d = 4; // 通过赋值创建属性时 enumerable 默认为 true Object.defineProperty(o, Symbol.for("e"), { value: 5, enumerable: true, diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.md b/files/zh-cn/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.md index 52ec6308842290..d98708adc8f9fc 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/object/getownpropertydescriptors/index.md @@ -52,7 +52,7 @@ Object.getOwnPropertyDescriptors(obj) ```js Object.create( Object.getPrototypeOf(obj), - Object.getOwnPropertyDescriptors(obj) + Object.getOwnPropertyDescriptors(obj), ); ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/hasown/index.md b/files/zh-cn/web/javascript/reference/global_objects/object/hasown/index.md index 9885d194fd2b80..0194dc6cc9d8f3 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/hasown/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/object/hasown/index.md @@ -42,16 +42,16 @@ Object.hasOwn(obj, prop) ```js const example = {}; -Object.hasOwn(example, 'prop'); // false——目标对象的属性 'prop' 未被定义 +Object.hasOwn(example, "prop"); // false——目标对象的属性 'prop' 未被定义 -example.prop = 'exists'; -Object.hasOwn(example, 'prop'); // true——目标对象的属性 'prop' 已被定义 +example.prop = "exists"; +Object.hasOwn(example, "prop"); // true——目标对象的属性 'prop' 已被定义 example.prop = null; -Object.hasOwn(example, 'prop'); // true——目标对象本身的属性存在,值为 null +Object.hasOwn(example, "prop"); // true——目标对象本身的属性存在,值为 null example.prop = undefined; -Object.hasOwn(example, 'prop'); // true——目标对象本身的属性存在,值为 undefined +Object.hasOwn(example, "prop"); // true——目标对象本身的属性存在,值为 undefined ``` ### 直接属性和继承属性 @@ -60,17 +60,17 @@ Object.hasOwn(example, 'prop'); // true——目标对象本身的属性存在 ```js const example = {}; -example.prop = 'exists'; +example.prop = "exists"; // `hasOwn` 静态方法只会对目标对象的直接属性返回 true: -Object.hasOwn(example, 'prop'); // 返回 true -Object.hasOwn(example, 'toString'); // 返回 false -Object.hasOwn(example, 'hasOwnProperty'); // 返回 false +Object.hasOwn(example, "prop"); // 返回 true +Object.hasOwn(example, "toString"); // 返回 false +Object.hasOwn(example, "hasOwnProperty"); // 返回 false // `in` 运算符对目标对象的直接属性或继承属性均会返回 true: -'prop' in example; // 返回 true -'toString' in example; // 返回 true -'hasOwnProperty' in example; // 返回 true +"prop" in example; // 返回 true +"toString" in example; // 返回 true +"hasOwnProperty" in example; // 返回 true ``` ### 迭代对象的属性 @@ -100,9 +100,9 @@ for (const name in example) { {{jsxref("Array")}} 中的元素被定义为直接属性,所以你可以使用 `hasOwn()` 方法去检查一个指定的索引是否存在: ```js -const fruits = ['Apple', 'Banana','Watermelon', 'Orange']; -Object.hasOwn(fruits, 3); // true ('Orange') -Object.hasOwn(fruits, 4); // false——没有定义的 +const fruits = ["Apple", "Banana", "Watermelon", "Orange"]; +Object.hasOwn(fruits, 3); // true ('Orange') +Object.hasOwn(fruits, 4); // false——没有定义的 ``` ### hasOwnProperty 的问题案例 @@ -114,10 +114,10 @@ const foo = { hasOwnProperty() { return false; }, - bar: 'The dragons be out of office', + bar: "The dragons be out of office", }; -if (Object.hasOwn(foo, 'bar')) { +if (Object.hasOwn(foo, "bar")) { console.log(foo.bar); //true——重新实现 hasOwnProperty() 不会影响 Object } ``` @@ -126,8 +126,8 @@ if (Object.hasOwn(foo, 'bar')) { ```js const foo = Object.create(null); -foo.prop = 'exists'; -if (Object.hasOwn(foo, 'prop')) { +foo.prop = "exists"; +if (Object.hasOwn(foo, "prop")) { console.log(foo.prop); //true——无论对象是如何创建的,它都可以运行。 } ``` diff --git a/files/zh-cn/web/javascript/reference/global_objects/object/setprototypeof/index.md b/files/zh-cn/web/javascript/reference/global_objects/object/setprototypeof/index.md index 4929433f3e93e2..263397802c5e71 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/object/setprototypeof/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/object/setprototypeof/index.md @@ -83,16 +83,16 @@ Object.setPrototypeOf(SuperHero.prototype, Human.prototype); Human.prototype.speak = function () { return `${this.name} says hello.`; -} +}; SuperHero.prototype.fly = function () { return `${this.name} is flying.`; -} +}; -const superMan = new SuperHero('Clark Kent', 1); +const superMan = new SuperHero("Clark Kent", 1); console.log(superMan.fly()); -console.log(superMan.speak()) +console.log(superMan.speak()); ``` 上面的类继承(使用 class)和伪类继承(使用带有 `prototype` 属性的构造函数)的相似性已在[继承与原型链](/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain#使用不同的方法来创建对象和生成原型链)中提到。 diff --git a/files/zh-cn/web/javascript/reference/global_objects/parsefloat/index.md b/files/zh-cn/web/javascript/reference/global_objects/parsefloat/index.md index f904f48ea21c39..df7398dbb7ac03 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/parsefloat/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/parsefloat/index.md @@ -47,12 +47,16 @@ parseFloat(string) ```js parseFloat(3.14); -parseFloat('3.14'); -parseFloat(' 3.14 '); -parseFloat('314e-2'); -parseFloat('0.0314E+2'); -parseFloat('3.14some non-digit characters'); -parseFloat({ toString: function() { return "3.14" } }); +parseFloat("3.14"); +parseFloat(" 3.14 "); +parseFloat("314e-2"); +parseFloat("0.0314E+2"); +parseFloat("3.14some non-digit characters"); +parseFloat({ + toString: function () { + return "3.14"; + }, +}); ``` ### `parseFloat` 返回 NaN @@ -69,7 +73,7 @@ parseFloat("FF2"); ```js parseFloat(900719925474099267n); -parseFloat('900719925474099267n'); +parseFloat("900719925474099267n"); ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/parseint/index.md b/files/zh-cn/web/javascript/reference/global_objects/parseint/index.md index abe68d9d07225c..f9efcb2921b93f 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/parseint/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/parseint/index.md @@ -74,7 +74,7 @@ parseInt("0xF", 16); parseInt("F", 16); parseInt("17", 8); parseInt(021, 8); -parseInt("015", 10); // parseInt(015, 8); 返回 13 +parseInt("015", 10); // parseInt(015, 8); 返回 13 parseInt(15.99, 10); parseInt("15,123", 10); parseInt("FXX123", 16); @@ -89,7 +89,7 @@ parseInt("12", 13); ```js parseInt("Hello", 8); // 根本就不是数值 -parseInt("546", 2); // 除了“0、1”外,其他数字都不是有效二进制数字 +parseInt("546", 2); // 除了“0、1”外,其他数字都不是有效二进制数字 ``` 以下例子均返回 `-15`: @@ -117,7 +117,7 @@ parseInt(0.00000000000434, 10); // 非常小的数值变成 4 下面的例子返回 `224` ```js -parseInt("0e0",16); +parseInt("0e0", 16); ``` ## 没有指定 `radix` 参数时的八进制解析 @@ -148,19 +148,18 @@ ECMAScript 5 规范不再允许 `parseInt` 函数的实现环境把以 `0` 字 ```js filterInt = function (value) { - if(/^(\-|\+)?([0-9]+|Infinity)$/.test(value)) - return Number(value); + if (/^(\-|\+)?([0-9]+|Infinity)$/.test(value)) return Number(value); return NaN; -} - -console.log(filterInt('421')); // 421 -console.log(filterInt('-421')); // -421 -console.log(filterInt('+421')); // 421 -console.log(filterInt('Infinity')); // Infinity -console.log(filterInt('421e+0')); // NaN -console.log(filterInt('421hop')); // NaN -console.log(filterInt('hop1.61803398875')); // NaN -console.log(filterInt('1.61803398875')); // NaN +}; + +console.log(filterInt("421")); // 421 +console.log(filterInt("-421")); // -421 +console.log(filterInt("+421")); // 421 +console.log(filterInt("Infinity")); // Infinity +console.log(filterInt("421e+0")); // NaN +console.log(filterInt("421hop")); // NaN +console.log(filterInt("hop1.61803398875")); // NaN +console.log(filterInt("1.61803398875")); // NaN ``` ## 规范 diff --git a/files/zh-cn/web/javascript/reference/global_objects/promise/index.md b/files/zh-cn/web/javascript/reference/global_objects/promise/index.md index 8198e551a868b4..9aee27771feb62 100644 --- a/files/zh-cn/web/javascript/reference/global_objects/promise/index.md +++ b/files/zh-cn/web/javascript/reference/global_objects/promise/index.md @@ -15,9 +15,9 @@ slug: Web/JavaScript/Reference/Global_Objects/Promise 一个 `Promise` 必然处于以下几种状态之一: -- *待定(pending)*:初始状态,既没有被兑现,也没有被拒绝。 -- *已兑现(fulfilled)*:意味着操作成功完成。 -- *已拒绝(rejected)*:意味着操作失败。 +- _待定(pending)_:初始状态,既没有被兑现,也没有被拒绝。 +- _已兑现(fulfilled)_:意味着操作成功完成。 +- _已拒绝(rejected)_:意味着操作失败。 一个待定的 Promise *最终状态*可以是*已兑现*并返回一个值,或者是*已拒绝*并返回一个原因(错误)。当其中任意一种情况发生时,通过 Promise 的 `then` 方法串联的处理程序将被调用。如果绑定相应处理程序时 Promise 已经兑现或拒绝,这处理程序将被立即调用,因此在异步操作完成和绑定处理程序之间不存在竞态条件。 @@ -333,10 +333,13 @@ function testPromise() { `${thisPromiseCount}) Promise constructor
        `, ); // 这只是一个创建异步操作的示例 - setTimeout(() => { - // We fulfill the promise - resolve(thisPromiseCount); - }, Math.random() * 2000 + 1000); + setTimeout( + () => { + // We fulfill the promise + resolve(thisPromiseCount); + }, + Math.random() * 2000 + 1000, + ); }); // 我们使用 then() 来定义 Promise 被解决时的操作, @@ -373,7 +376,7 @@ btn.addEventListener("click", testPromise); 我们可以尝试在文档中嵌入 [` +