Some text to copy and paste.
-Go on, try pasting some content into this editable paragraph and see what happens!
+
+ Go on, try pasting some content into this editable paragraph and see what
+ happens!
+
-
Some sample text. Try inserting line breaks, or deleting text in different ways, or pasting different content in.
-
+
Input type:
+
+
+ Some sample text. Try inserting line breaks, or deleting text in different
+ ways, or pasting different content in.
+
+
A sample
bulleted
@@ -40,9 +45,9 @@ var aString = inputEvent.inputType;
### JavaScript
```js
-const log = document.getElementById('log');
-const editable = document.querySelector('div[contenteditable]');
-editable.addEventListener('input', logInputType);
+const log = document.getElementById("log");
+const editable = document.querySelector("div[contenteditable]");
+editable.addEventListener("input", logInputType);
function logInputType(event) {
log.textContent = `Input type: ${event.inputType}`;
diff --git a/files/zh-cn/web/api/installevent/index.md b/files/zh-cn/web/api/installevent/index.md
index b447e9c4d67d51..20814147f5356b 100644
--- a/files/zh-cn/web/api/installevent/index.md
+++ b/files/zh-cn/web/api/installevent/index.md
@@ -38,28 +38,38 @@ _从它的父类{{domxref("ExtendableEvent")}}继承方法。_
```js
var CACHE_VERSION = 1;
var CURRENT_CACHES = {
- prefetch: 'prefetch-cache-v' + CACHE_VERSION
+ prefetch: "prefetch-cache-v" + CACHE_VERSION,
};
-self.addEventListener('install', function(event) {
+self.addEventListener("install", function (event) {
var urlsToPrefetch = [
- './static/pre_fetched.txt',
- './static/pre_fetched.html',
- 'https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif'
+ "./static/pre_fetched.txt",
+ "./static/pre_fetched.html",
+ "https://www.chromium.org/_/rsrc/1302286216006/config/customLogo.gif",
];
-console.log('Handling install event. Resources to pre-fetch:', urlsToPrefetch);
+ console.log(
+ "Handling install event. Resources to pre-fetch:",
+ urlsToPrefetch,
+ );
event.waitUntil(
- caches.open(CURRENT_CACHES['prefetch']).then(function(cache) {
- cache.addAll(urlsToPrefetch.map(function(urlToPrefetch) {
- return new Request(urlToPrefetch, {mode: 'no-cors'});
- })).then(function() {
- console.log('All resources have been fetched and cached.');
- });
- }).catch(function(error) {
- console.error('Pre-fetching failed:', error);
- })
+ caches
+ .open(CURRENT_CACHES["prefetch"])
+ .then(function (cache) {
+ cache
+ .addAll(
+ urlsToPrefetch.map(function (urlToPrefetch) {
+ return new Request(urlToPrefetch, { mode: "no-cors" });
+ }),
+ )
+ .then(function () {
+ console.log("All resources have been fetched and cached.");
+ });
+ })
+ .catch(function (error) {
+ console.error("Pre-fetching failed:", error);
+ }),
);
});
```
diff --git a/files/zh-cn/web/api/intersection_observer_api/index.md b/files/zh-cn/web/api/intersection_observer_api/index.md
index 4537b0a588de50..b6c8431c075459 100644
--- a/files/zh-cn/web/api/intersection_observer_api/index.md
+++ b/files/zh-cn/web/api/intersection_observer_api/index.md
@@ -41,10 +41,10 @@ Intersection Observer API 允许你配置一个回调函数,当以下情况发
```js
let options = {
- root: document.querySelector('#scrollArea'),
- rootMargin: '0px',
- threshold: 1.0
-}
+ root: document.querySelector("#scrollArea"),
+ rootMargin: "0px",
+ threshold: 1.0,
+};
let observer = new IntersectionObserver(callback, options);
```
@@ -67,7 +67,7 @@ let observer = new IntersectionObserver(callback, options);
创建一个 observer 后需要给定一个目标元素进行观察。
```js
-let target = document.querySelector('#listItem');
+let target = document.querySelector("#listItem");
observer.observe(target);
```
@@ -76,8 +76,8 @@ observer.observe(target);
只要目标满足为 IntersectionObserver 指定的阈值,就会调用回调。回调接收 {{domxref("IntersectionObserverEntry")}} 对象和观察者的列表:
```js
-let callback =(entries, observer) => {
- entries.forEach(entry => {
+let callback = (entries, observer) => {
+ entries.forEach((entry) => {
// Each entry describes an intersection change for one observed target element:
// entry.boundingClientRect
// entry.intersectionRatio
@@ -137,8 +137,7 @@ Note that it's possible to have a non-zero intersection rectangle, which can hap
```
@@ -182,7 +181,10 @@ Note that it's possible to have a non-zero intersection rectangle, which can hap
}
.label {
- font: 14px "Open Sans", "Arial", sans-serif;
+ font:
+ 14px "Open Sans",
+ "Arial",
+ sans-serif;
position: absolute;
margin: 0;
background-color: rgba(255, 255, 255, 0.7);
@@ -225,7 +227,7 @@ startup = () => {
let observerOptions = {
root: null,
rootMargin: "0px",
- threshold: []
+ threshold: [],
};
// An array of threshold sets for each of the boxes. The
@@ -237,45 +239,51 @@ startup = () => {
[],
[0.5],
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],
- [0, 0.25, 0.5, 0.75, 1.0]
+ [0, 0.25, 0.5, 0.75, 1.0],
];
- for (let i=0; i<=1.0; i+= 0.01) {
+ for (let i = 0; i <= 1.0; i += 0.01) {
thresholdSets[0].push(i);
}
// Add each box, creating a new observer for each
- for (let i=0; i<4; i++) {
- let template = document.querySelector("#boxTemplate").content.cloneNode(true);
- let boxID = "box" + (i+1);
+ for (let i = 0; i < 4; i++) {
+ let template = document
+ .querySelector("#boxTemplate")
+ .content.cloneNode(true);
+ let boxID = "box" + (i + 1);
template.querySelector(".sampleBox").id = boxID;
wrapper.appendChild(document.importNode(template, true));
// Set up the observer for this box
observerOptions.threshold = thresholdSets[i];
- observers[i] = new IntersectionObserver(intersectionCallback, observerOptions);
+ observers[i] = new IntersectionObserver(
+ intersectionCallback,
+ observerOptions,
+ );
observers[i].observe(document.querySelector("#" + boxID));
}
// Scroll to the starting position
- document.scrollingElement.scrollTop = wrapper.firstElementChild.getBoundingClientRect().top + window.scrollY;
+ document.scrollingElement.scrollTop =
+ wrapper.firstElementChild.getBoundingClientRect().top + window.scrollY;
document.scrollingElement.scrollLeft = 750;
-}
+};
intersectionCallback = (entries) => {
entries.forEach((entry) => {
let box = entry.target;
- let visiblePct = (Math.floor(entry.intersectionRatio * 100)) + "%";
+ let visiblePct = Math.floor(entry.intersectionRatio * 100) + "%";
box.querySelector(".topLeft").innerHTML = visiblePct;
box.querySelector(".topRight").innerHTML = visiblePct;
box.querySelector(".bottomLeft").innerHTML = visiblePct;
box.querySelector(".bottomRight").innerHTML = visiblePct;
});
-}
+};
startup();
```
@@ -332,9 +340,7 @@ The HTML for this example is very short, with a primary element which is the box
```html
-
- Welcome to The Box!
-
+
Welcome to The Box!
```
@@ -346,7 +352,9 @@ The CSS isn't terribly important for the purposes of this example; it lays out t
#box {
background-color: rgba(40, 40, 190, 255);
border: 4px solid rgb(20, 20, 120);
- transition: background-color 1s, border 1s;
+ transition:
+ background-color 1s,
+ border 1s;
width: 350px;
height: 350px;
display: flex;
@@ -387,11 +395,15 @@ let increasingColor = "rgba(40, 40, 190, ratio)";
let decreasingColor = "rgba(190, 40, 40, ratio)";
// Set things up
-window.addEventListener("load", (event) => {
- boxElement = document.querySelector("#box");
-
- createObserver();
-}, false);
+window.addEventListener(
+ "load",
+ (event) => {
+ boxElement = document.querySelector("#box");
+
+ createObserver();
+ },
+ false,
+);
```
The constants and variables we set up here are:
@@ -418,7 +430,7 @@ function createObserver() {
let options = {
root: null,
rootMargin: "0px",
- threshold: buildThresholdList()
+ threshold: buildThresholdList(),
};
observer = new IntersectionObserver(handleIntersect, options);
@@ -443,8 +455,8 @@ function buildThresholdList() {
let thresholds = [];
let numSteps = 20;
- for (let i=1.0; i<=numSteps; i++) {
- let ratio = i/numSteps;
+ for (let i = 1.0; i <= numSteps; i++) {
+ let ratio = i / numSteps;
thresholds.push(ratio);
}
@@ -478,9 +490,15 @@ When the browser detects that the target element (in our case, the one with the
function handleIntersect(entries, observer) {
entries.forEach((entry) => {
if (entry.intersectionRatio > prevRatio) {
- entry.target.style.backgroundColor = increasingColor.replace("ratio", entry.intersectionRatio);
+ entry.target.style.backgroundColor = increasingColor.replace(
+ "ratio",
+ entry.intersectionRatio,
+ );
} else {
- entry.target.style.backgroundColor = decreasingColor.replace("ratio", entry.intersectionRatio);
+ entry.target.style.backgroundColor = decreasingColor.replace(
+ "ratio",
+ entry.intersectionRatio,
+ );
}
prevRatio = entry.intersectionRatio;
diff --git a/files/zh-cn/web/api/intersection_observer_api/timing_element_visibility/index.md b/files/zh-cn/web/api/intersection_observer_api/timing_element_visibility/index.md
index 41657c84ef0b7c..594ca60d08b694 100644
--- a/files/zh-cn/web/api/intersection_observer_api/timing_element_visibility/index.md
+++ b/files/zh-cn/web/api/intersection_observer_api/timing_element_visibility/index.md
@@ -34,8 +34,7 @@ The site's structure is not too complicated. We'll be using CSS Grid to style an
-
-
+
```
@@ -236,11 +235,10 @@ function startup() {
let observerOptions = {
root: null,
rootMargin: "0px",
- threshold: [0.0, 0.75]
+ threshold: [0.0, 0.75],
};
- adObserver = new IntersectionObserver(intersectionCallback,
- observerOptions);
+ adObserver = new IntersectionObserver(intersectionCallback, observerOptions);
buildContents();
refreshIntervalID = window.setInterval(handleRefreshInterval, 1000);
@@ -267,13 +265,13 @@ function handleVisibilityChange() {
if (!previouslyVisibleAds) {
previouslyVisibleAds = visibleAds;
visibleAds = [];
- previouslyVisibleAds.forEach(function(adBox) {
+ previouslyVisibleAds.forEach(function (adBox) {
updateAdTimer(adBox);
adBox.dataset.lastViewStarted = 0;
});
}
} else {
- previouslyVisibleAds.forEach(function(adBox) {
+ previouslyVisibleAds.forEach(function (adBox) {
adBox.dataset.lastViewStarted = performance.now();
});
visibleAds = previouslyVisibleAds;
@@ -294,7 +292,7 @@ Once per pass through the browser's event loop, each {{domxref("IntersectionObse
```js
function intersectionCallback(entries) {
- entries.forEach(function(entry) {
+ entries.forEach(function (entry) {
let adBox = entry.target;
if (entry.isIntersecting) {
@@ -304,7 +302,10 @@ function intersectionCallback(entries) {
}
} else {
visibleAds.delete(adBox);
- if ((entry.intersectionRatio === 0.0) && (adBox.dataset.totalViewTime >= 60000)) {
+ if (
+ entry.intersectionRatio === 0.0 &&
+ adBox.dataset.totalViewTime >= 60000
+ ) {
replaceAd(adBox);
}
}
@@ -324,7 +325,7 @@ Our interval handler, `handleRefreshInterval()`, is called about once per second
function handleRefreshInterval() {
let redrawList = [];
- visibleAds.forEach(function(adBox) {
+ visibleAds.forEach(function (adBox) {
let previousTime = adBox.dataset.totalViewTime;
updateAdTimer(adBox);
@@ -334,8 +335,8 @@ function handleRefreshInterval() {
});
if (redrawList.length) {
- window.requestAnimationFrame(function(time) {
- redrawList.forEach(function(adBox) {
+ window.requestAnimationFrame(function (time) {
+ redrawList.forEach(function (adBox) {
drawAdTimer(adBox);
});
});
@@ -361,7 +362,8 @@ function updateAdTimer(adBox) {
if (lastStarted) {
let diff = currentTime - lastStarted;
- adBox.dataset.totalViewTime = parseFloat(adBox.dataset.totalViewTime) + diff;
+ adBox.dataset.totalViewTime =
+ parseFloat(adBox.dataset.totalViewTime) + diff;
}
adBox.dataset.lastViewStarted = currentTime;
@@ -405,7 +407,8 @@ This code finds the ad's timer using its ID, `"timer"`, and computes the number
The `buildContents()` function is called by the [startup code](#setting_up) to select and insert into the document the articles and ads to be presented:
```js
-let loremIpsum = "
Lorem ipsum dolor sit amet, consectetur adipiscing" +
+let loremIpsum =
+ "
Lorem ipsum dolor sit amet, consectetur adipiscing" +
" elit. Cras at sem diam. Vestibulum venenatis massa in tincidunt" +
" egestas. Morbi eu lorem vel est sodales auctor hendrerit placerat" +
" risus. Etiam rutrum faucibus sem, vitae mattis ipsum ullamcorper" +
@@ -414,7 +417,7 @@ let loremIpsum = "
Lorem ipsum dolor sit amet, consectetur adipiscing" +
" cursus nunc.
";
function buildContents() {
- for (let i=0; i<5; i++) {
+ for (let i = 0; i < 5; i++) {
contentBox.appendChild(createArticle(loremIpsum));
if (!(i % 2)) {
@@ -445,7 +448,7 @@ function createArticle(contents) {
articleElem.appendChild(titleElem);
articleElem.innerHTML += contents;
- nextArticleID +=1 ;
+ nextArticleID += 1;
return articleElem;
}
@@ -463,27 +466,27 @@ function loadRandomAd(replaceBox) {
{
bgcolor: "#cec",
title: "Eat Green Beans",
- body: "Make your mother proud—they're good for you!"
+ body: "Make your mother proud—they're good for you!",
},
{
bgcolor: "aquamarine",
title: "MillionsOfFreeBooks.whatever",
- body: "Read classic literature online free!"
+ body: "Read classic literature online free!",
},
{
bgcolor: "lightgrey",
title: "3.14 Shades of Gray: A novel",
- body: "Love really does make the world go round..."
+ body: "Love really does make the world go round...",
},
{
bgcolor: "#fee",
title: "Flexbox Florist",
- body: "When life's layout gets complicated, send flowers."
- }
+ body: "When life's layout gets complicated, send flowers.",
+ },
];
let adBox, title, body, timerElem;
- let ad = ads[Math.floor(Math.random()*ads.length)];
+ let ad = ads[Math.floor(Math.random() * ads.length)];
if (replaceBox) {
adObserver.unobserve(replaceBox);
@@ -512,7 +515,7 @@ function loadRandomAd(replaceBox) {
adBox.dataset.totalViewTime = 0;
adBox.dataset.lastViewStarted = 0;
- timerElem.className="timer";
+ timerElem.className = "timer";
timerElem.innerText = "0:00";
if (!replaceBox) {
@@ -560,8 +563,13 @@ function replaceAd(adBox) {
updateAdTimer(adBox);
- visibleTime = adBox.dataset.totalViewTime
- console.log(" Replacing ad: " + adBox.querySelector("h2").innerText + " - visible for " + visibleTime)
+ visibleTime = adBox.dataset.totalViewTime;
+ console.log(
+ " Replacing ad: " +
+ adBox.querySelector("h2").innerText +
+ " - visible for " +
+ visibleTime,
+ );
loadRandomAd(adBox);
}
diff --git a/files/zh-cn/web/api/intersectionobserver/index.md b/files/zh-cn/web/api/intersectionobserver/index.md
index 6e851429ea7976..2a1a151d76dfbe 100644
--- a/files/zh-cn/web/api/intersectionobserver/index.md
+++ b/files/zh-cn/web/api/intersectionobserver/index.md
@@ -43,10 +43,10 @@ const intersectionObserver = new IntersectionObserver((entries) => {
if (entries[0].intersectionRatio <= 0) return;
loadItems(10);
- console.log('Loaded new items');
+ console.log("Loaded new items");
});
// 开始监听
-intersectionObserver.observe(document.querySelector('.scrollerFooter'));
+intersectionObserver.observe(document.querySelector(".scrollerFooter"));
```
## 规范
diff --git a/files/zh-cn/web/api/intersectionobserver/observe/index.md b/files/zh-cn/web/api/intersectionobserver/observe/index.md
index d0d33eb537c5ed..08de98a499fd51 100644
--- a/files/zh-cn/web/api/intersectionobserver/observe/index.md
+++ b/files/zh-cn/web/api/intersectionobserver/observe/index.md
@@ -29,24 +29,24 @@ IntersectionObserver.observe(targetElement);
```js
// Register IntersectionObserver
-const io = new IntersectionObserver(entries => {
- entries.forEach(entry => {
+const io = new IntersectionObserver((entries) => {
+ entries.forEach((entry) => {
// Add 'active' class if observation target is inside viewport
if (entry.intersectionRatio > 0) {
- entry.target.classList.add('active');
+ entry.target.classList.add("active");
}
// Remove 'active' class otherwise
else {
- entry.target.classList.remove('active');
+ entry.target.classList.remove("active");
}
- })
-})
+ });
+});
// Declares what to observe, and observes its properties.
-const boxElList = document.querySelectorAll('.box');
+const boxElList = document.querySelectorAll(".box");
boxElList.forEach((el) => {
- io.observe(el);
-})
+ io.observe(el);
+});
```
## 规范
diff --git a/files/zh-cn/web/api/keyboard/index.md b/files/zh-cn/web/api/keyboard/index.md
index 8319dd02032b82..b4f2f325db758d 100644
--- a/files/zh-cn/web/api/keyboard/index.md
+++ b/files/zh-cn/web/api/keyboard/index.md
@@ -29,10 +29,9 @@ The following example demonstrates how to get the location- or layout-specific s
```js
if (navigator.keyboard) {
var keyboard = navigator.keyboard;
- keyboard.getLayoutMap()
- .then(keyboardLayoutMap => {
- var upKey = keyboardLayoutMap.get('KeyW');
- window.alert('Press ' + upKey + ' to move up.');
+ keyboard.getLayoutMap().then((keyboardLayoutMap) => {
+ var upKey = keyboardLayoutMap.get("KeyW");
+ window.alert("Press " + upKey + " to move up.");
});
} else {
// Do something else.
diff --git a/files/zh-cn/web/javascript/reference/classes/constructor/index.md b/files/zh-cn/web/javascript/reference/classes/constructor/index.md
index 519a5dc6df2acb..fd96c56c1bd80d 100644
--- a/files/zh-cn/web/javascript/reference/classes/constructor/index.md
+++ b/files/zh-cn/web/javascript/reference/classes/constructor/index.md
@@ -33,21 +33,21 @@ constructor([arguments]) { ... }
```js
class Square extends Polygon {
- constructor(length) {
- // 在这里,它调用了父类的构造函数,并将 lengths 提供给 Polygon 的"width"和"height"
- super(length, length);
- // 注意:在派生类中,必须先调用 super() 才能使用 "this"。
- // 忽略这个,将会导致一个引用错误。
- this.name = 'Square';
- }
- get area() {
- return this.height * this.width;
- }
- set area(value) {
- // 注意:不可使用 this.area = value
- // 否则会导致循环 call setter 方法导致爆栈
- this._area = value;
- }
+ constructor(length) {
+ // 在这里,它调用了父类的构造函数,并将 lengths 提供给 Polygon 的"width"和"height"
+ super(length, length);
+ // 注意:在派生类中,必须先调用 super() 才能使用 "this"。
+ // 忽略这个,将会导致一个引用错误。
+ this.name = "Square";
+ }
+ get area() {
+ return this.height * this.width;
+ }
+ set area(value) {
+ // 注意:不可使用 this.area = value
+ // 否则会导致循环 call setter 方法导致爆栈
+ this._area = value;
+ }
}
```
@@ -57,15 +57,15 @@ class Square extends Polygon {
```js
class Polygon {
- constructor() {
- this.name = "Polygon";
- }
+ constructor() {
+ this.name = "Polygon";
+ }
}
class Square extends Polygon {
- constructor() {
- super();
- }
+ constructor() {
+ super();
+ }
}
class Rectangle {}
diff --git a/files/zh-cn/web/javascript/reference/classes/extends/index.md b/files/zh-cn/web/javascript/reference/classes/extends/index.md
index 0b00993167e626..ad687b2e9bce9e 100644
--- a/files/zh-cn/web/javascript/reference/classes/extends/index.md
+++ b/files/zh-cn/web/javascript/reference/classes/extends/index.md
@@ -33,7 +33,7 @@ class Square extends Polygon {
super(length, length);
// Note: In derived classes, super() must be called before you
// can use 'this'. Leaving this out will cause a reference error.
- this.name = 'Square';
+ this.name = "Square";
}
get area() {
@@ -53,8 +53,23 @@ class myDate extends Date {
}
getFormattedDate() {
- var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
- return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
+ var months = [
+ "Jan",
+ "Feb",
+ "Mar",
+ "Apr",
+ "May",
+ "Jun",
+ "Jul",
+ "Aug",
+ "Sep",
+ "Oct",
+ "Nov",
+ "Dec",
+ ];
+ return (
+ this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear()
+ );
}
}
```
@@ -69,7 +84,7 @@ class nullExtends extends null {
}
Object.getPrototypeOf(nullExtends); // Function.prototype
-Object.getPrototypeOf(nullExtends.prototype) // null
+Object.getPrototypeOf(nullExtends.prototype); // null
new nullExtends(); //ReferenceError: this is not defined
```
diff --git a/files/zh-cn/web/javascript/reference/classes/index.md b/files/zh-cn/web/javascript/reference/classes/index.md
index 9f46d28a15716e..bf5ce695dc20e1 100644
--- a/files/zh-cn/web/javascript/reference/classes/index.md
+++ b/files/zh-cn/web/javascript/reference/classes/index.md
@@ -82,19 +82,19 @@ console.log(Rectangle.name);
```js
class Rectangle {
- // constructor
- constructor(height, width) {
- this.height = height;
- this.width = width;
- }
- // Getter
- get area() {
- return this.calcArea()
- }
- // Method
- calcArea() {
- return this.height * this.width;
- }
+ // constructor
+ constructor(height, width) {
+ this.height = height;
+ this.width = width;
+ }
+ // Getter
+ get area() {
+ return this.calcArea();
+ }
+ // Method
+ calcArea() {
+ return this.height * this.width;
+ }
}
const square = new Rectangle(10, 10);
@@ -108,22 +108,22 @@ console.log(square.area);
```js
class Point {
- constructor(x, y) {
- this.x = x;
- this.y = y;
- }
-
- static displayName = "Point";
-
- static distance(a, b) {
- const dx = a.x - b.x;
- const dy = a.y - b.y;
- return Math.hypot(dx, dy);
- }
+ constructor(x, y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ static displayName = "Point";
+
+ static distance(a, b) {
+ const dx = a.x - b.x;
+ const dy = a.y - b.y;
+ return Math.hypot(dx, dy);
+ }
}
const p1 = new Point(5, 5);
-const p2 = new Point(10,10);
+const p2 = new Point(10, 10);
p1.displayName;
// undefined
p1.distance;
@@ -154,7 +154,7 @@ obj.speak(); // Animal {}
let speak = obj.speak;
speak(); // undefined
-Animal.eat() // class Animal
+Animal.eat(); // class Animal
let eat = Animal.eat;
eat(); // undefined
```
@@ -164,15 +164,15 @@ eat(); // undefined
严格模式下不会发生自动装箱,_this_ 值将保留传入状态。
```js
-function Animal() { }
+function Animal() {}
-Animal.prototype.speak = function() {
+Animal.prototype.speak = function () {
return this;
-}
+};
-Animal.eat = function() {
+Animal.eat = function () {
return this;
-}
+};
let obj = new Animal();
let speak = obj.speak;
@@ -275,8 +275,8 @@ class Dog extends Animal {
}
}
-var d = new Dog('Mitzie');
-d.speak();// 'Mitzie barks.'
+var d = new Dog("Mitzie");
+d.speak(); // 'Mitzie barks.'
```
如果子类中定义了构造函数,那么它必须先调用 `super()` 才能使用 `this` 。
@@ -284,22 +284,22 @@ d.speak();// 'Mitzie barks.'
也可以继承传统的基于函数的“类”:
```js
-function Animal (name) {
+function Animal(name) {
this.name = name;
}
Animal.prototype.speak = function () {
- console.log(this.name + ' makes a noise.');
-}
+ console.log(this.name + " makes a noise.");
+};
class Dog extends Animal {
speak() {
super.speak();
- console.log(this.name + ' barks.');
+ console.log(this.name + " barks.");
}
}
-var d = new Dog('Mitzie');
-d.speak();//Mitzie makes a noise. Mitzie barks.
+var d = new Dog("Mitzie");
+d.speak(); //Mitzie makes a noise. Mitzie barks.
```
请注意,类不能继承常规对象(不可构造的)。如果要继承常规对象,可以改用{{jsxref("Object.setPrototypeOf()")}}:
@@ -307,8 +307,8 @@ d.speak();//Mitzie makes a noise. Mitzie barks.
```js
var Animal = {
speak() {
- console.log(this.name + ' makes a noise.');
- }
+ console.log(this.name + " makes a noise.");
+ },
};
class Dog {
@@ -317,9 +317,9 @@ class Dog {
}
}
-Object.setPrototypeOf(Dog.prototype, Animal);// 如果不这样做,在调用 speak 时会返回 TypeError
+Object.setPrototypeOf(Dog.prototype, Animal); // 如果不这样做,在调用 speak 时会返回 TypeError
-var d = new Dog('Mitzie');
+var d = new Dog("Mitzie");
d.speak(); // Mitzie makes a noise.
```
@@ -332,10 +332,12 @@ d.speak(); // Mitzie makes a noise.
```js
class MyArray extends Array {
// Overwrite species to the parent Array constructor
- static get [Symbol.species]() { return Array; }
+ static get [Symbol.species]() {
+ return Array;
+ }
}
-var a = new MyArray(1,2,3);
-var mapped = a.map(x => x * x);
+var a = new MyArray(1, 2, 3);
+var mapped = a.map((x) => x * x);
console.log(mapped instanceof MyArray);
// false
@@ -354,14 +356,14 @@ class Cat {
}
speak() {
- console.log(this.name + ' makes a noise.');
+ console.log(this.name + " makes a noise.");
}
}
class Lion extends Cat {
speak() {
super.speak();
- console.log(this.name + ' roars.');
+ console.log(this.name + " roars.");
}
}
```
@@ -373,20 +375,22 @@ class Lion extends Cat {
一个以超类作为输入的函数和一个继承该超类的子类作为输出可以用于在 ECMAScript 中实现混合:
```js
-var calculatorMixin = Base => class extends Base {
- calc() { }
-};
-
-var randomizerMixin = Base => class extends Base {
- randomize() { }
-};
+var calculatorMixin = (Base) =>
+ class extends Base {
+ calc() {}
+ };
+
+var randomizerMixin = (Base) =>
+ class extends Base {
+ randomize() {}
+ };
```
使用 mix-ins 的类可以像下面这样写:
```js
-class Foo { }
-class Bar extends calculatorMixin(randomizerMixin(Foo)) { }
+class Foo {}
+class Bar extends calculatorMixin(randomizerMixin(Foo)) {}
```
## 规范
diff --git a/files/zh-cn/web/javascript/reference/classes/private_class_fields/index.md b/files/zh-cn/web/javascript/reference/classes/private_class_fields/index.md
index b527900d36aa89..f90c3a912e6580 100644
--- a/files/zh-cn/web/javascript/reference/classes/private_class_fields/index.md
+++ b/files/zh-cn/web/javascript/reference/classes/private_class_fields/index.md
@@ -16,7 +16,7 @@ class ClassWithPrivateField {
class ClassWithPrivateMethod {
#privateMethod() {
- return 'hello world';
+ return "hello world";
}
}
@@ -26,7 +26,7 @@ class ClassWithPrivateStaticField {
class ClassWithPrivateStaticMethod {
static #privateStaticMethod() {
- return 'hello world';
+ return "hello world";
}
}
```
@@ -114,13 +114,15 @@ class BaseClassWithPrivateStaticField {
}
}
-class SubClass extends BaseClassWithPrivateStaticField { };
+class SubClass extends BaseClassWithPrivateStaticField {}
let error = null;
try {
- SubClass.basePublicStaticMethod()
-} catch(e) { error = e};
+ SubClass.basePublicStaticMethod();
+} catch (e) {
+ error = e;
+}
console.log(error instanceof TypeError);
// true
@@ -138,7 +140,7 @@ console.log(error);
```js
class ClassWithPrivateMethod {
#privateMethod() {
- return 'hello world';
+ return "hello world";
}
getPrivateMessage() {
@@ -165,7 +167,7 @@ class ClassWithPrivateAccessor {
}
constructor() {
- this.#decoratedMessage = 'hello world';
+ this.#decoratedMessage = "hello world";
console.log(this.#decoratedMessage);
}
}
diff --git a/files/zh-cn/web/javascript/reference/classes/public_class_fields/index.md b/files/zh-cn/web/javascript/reference/classes/public_class_fields/index.md
index 41985f2d8cfd91..c7e3d84552c029 100644
--- a/files/zh-cn/web/javascript/reference/classes/public_class_fields/index.md
+++ b/files/zh-cn/web/javascript/reference/classes/public_class_fields/index.md
@@ -11,16 +11,16 @@ slug: Web/JavaScript/Reference/Classes/Public_class_fields
```js
class ClassWithInstanceField {
- instanceField = 'instance field'
+ instanceField = "instance field";
}
class ClassWithStaticField {
- static staticField = 'static field'
+ static staticField = "static field";
}
class ClassWithPublicInstanceMethod {
publicMethod() {
- return 'hello world'
+ return "hello world";
}
}
```
@@ -35,22 +35,22 @@ class ClassWithPublicInstanceMethod {
```js
class ClassWithStaticField {
- static staticField = 'static field'
+ static staticField = "static field";
}
-console.log(ClassWithStaticField.staticField)
-// 预期输出值:"static field"
+console.log(ClassWithStaticField.staticField);
+// 预期输出值:"static field"
```
没有设定初始化的字段将默认被初始化为 `undefined`。
```js
class ClassWithStaticField {
- static staticField
+ static staticField;
}
-console.assert(Object.hasOwn(ClassWithStaticField, 'staticField'))
-console.log(ClassWithStaticField.staticField)
+console.assert(Object.hasOwn(ClassWithStaticField, "staticField"));
+console.log(ClassWithStaticField.staticField);
// 预期输出值:"undefined"
```
@@ -58,17 +58,17 @@ console.log(ClassWithStaticField.staticField)
```js
class ClassWithStaticField {
- static baseStaticField = 'base field'
+ static baseStaticField = "base field";
}
class SubClassWithStaticField extends ClassWithStaticField {
- static subStaticField = 'sub class field'
+ static subStaticField = "sub class field";
}
-console.log(SubClassWithStaticField.subStaticField)
+console.log(SubClassWithStaticField.subStaticField);
// 预期输出值:"sub class field"
-console.log(SubClassWithStaticField.baseStaticField)
+console.log(SubClassWithStaticField.baseStaticField);
// 预期输出值:"base field"
```
@@ -76,20 +76,22 @@ console.log(SubClassWithStaticField.baseStaticField)
```js
class ClassWithStaticField {
- static baseStaticField = 'base static field'
- static anotherBaseStaticField = this.baseStaticField
+ static baseStaticField = "base static field";
+ static anotherBaseStaticField = this.baseStaticField;
- static baseStaticMethod() { return 'base static method output' }
+ static baseStaticMethod() {
+ return "base static method output";
+ }
}
class SubClassWithStaticField extends ClassWithStaticField {
- static subStaticField = super.baseStaticMethod()
+ static subStaticField = super.baseStaticMethod();
}
-console.log(ClassWithStaticField.anotherBaseStaticField)
+console.log(ClassWithStaticField.anotherBaseStaticField);
// 预期输出值:"base static field"
-console.log(SubClassWithStaticField.subStaticField)
+console.log(SubClassWithStaticField.subStaticField);
// 预期输出值:"base static method output"
```
@@ -101,11 +103,11 @@ console.log(SubClassWithStaticField.subStaticField)
```js
class ClassWithInstanceField {
- instanceField = 'instance field'
+ instanceField = "instance field";
}
-const instance = new ClassWithInstanceField()
-console.log(instance.instanceField)
+const instance = new ClassWithInstanceField();
+console.log(instance.instanceField);
// 预期输出值:"instance field"
```
@@ -113,22 +115,22 @@ console.log(instance.instanceField)
```js
class ClassWithInstanceField {
- instanceField
+ instanceField;
}
-const instance = new ClassWithInstanceField()
-console.assert(Object.hasOwn(instance, 'instanceField'))
-console.log(instance.instanceField)
+const instance = new ClassWithInstanceField();
+console.assert(Object.hasOwn(instance, "instanceField"));
+console.log(instance.instanceField);
// 预期输出值:"undefined"
```
和属性(properties)一样,字段名可以由计算得出。
```js
-const PREFIX = 'prefix';
+const PREFIX = "prefix";
class ClassWithComputedFieldName {
- [`${PREFIX}Field`] = 'prefixed field';
+ [`${PREFIX}Field`] = "prefixed field";
}
const instance = new ClassWithComputedFieldName();
@@ -140,22 +142,24 @@ console.log(instance.prefixField);
```js
class ClassWithInstanceField {
- baseInstanceField = 'base field'
- anotherBaseInstanceField = this.baseInstanceField
- baseInstanceMethod() { return 'base method output' }
+ baseInstanceField = "base field";
+ anotherBaseInstanceField = this.baseInstanceField;
+ baseInstanceMethod() {
+ return "base method output";
+ }
}
class SubClassWithInstanceField extends ClassWithInstanceField {
- subInstanceField = super.baseInstanceMethod()
+ subInstanceField = super.baseInstanceMethod();
}
-const base = new ClassWithInstanceField()
-const sub = new SubClassWithInstanceField()
+const base = new ClassWithInstanceField();
+const sub = new SubClassWithInstanceField();
-console.log(base.anotherBaseInstanceField)
+console.log(base.anotherBaseInstanceField);
// 预期输出值:"base field"
-console.log(sub.subInstanceField)
+console.log(sub.subInstanceField);
// 预期输出值:"base method output"
```
@@ -163,11 +167,11 @@ console.log(sub.subInstanceField)
```js
class ClassWithInstanceField {
- instanceField = 'instance field';
+ instanceField = "instance field";
constructor() {
console.log(this.instanceField);
- this.instanceField = 'new value';
+ this.instanceField = "new value";
}
}
@@ -180,7 +184,7 @@ console.log(instance.instanceField); // "new value"
```js
class Base {
constructor() {
- console.log('Base constructor:', this.field);
+ console.log("Base constructor:", this.field);
}
}
@@ -188,7 +192,7 @@ class Derived extends Base {
field = 1;
constructor() {
super();
- console.log('Derived constructor:', this.field);
+ console.log("Derived constructor:", this.field);
}
}
@@ -233,7 +237,7 @@ const instance2 = new DerivedWithConstructor(); // Logs 1
```js
class ClassWithStaticMethod {
static staticMethod() {
- return 'static method has been called.';
+ return "static method has been called.";
}
}
@@ -250,12 +254,12 @@ console.log(ClassWithStaticMethod.staticMethod());
```js
class ClassWithPublicInstanceMethod {
publicMethod() {
- return 'hello world'
+ return "hello world";
}
}
-const instance = new ClassWithPublicInstanceMethod()
-console.log(instance.publicMethod())
+const instance = new ClassWithPublicInstanceMethod();
+console.log(instance.publicMethod());
// 预期输出值:"hello world"
```
@@ -265,9 +269,9 @@ console.log(instance.publicMethod())
```js
class ClassWithFancyMethods {
- *generatorMethod() { }
- async asyncMethod() { }
- async *asyncGeneratorMethod() { }
+ *generatorMethod() {}
+ async asyncMethod() {}
+ async *asyncGeneratorMethod() {}
}
```
@@ -275,20 +279,20 @@ class ClassWithFancyMethods {
```js
class BaseClass {
- msg = 'hello world'
+ msg = "hello world";
basePublicMethod() {
- return this.msg
+ return this.msg;
}
}
class SubClass extends BaseClass {
subPublicMethod() {
- return super.basePublicMethod()
+ return super.basePublicMethod();
}
}
-const instance = new SubClass()
-console.log(instance.subPublicMethod())
+const instance = new SubClass();
+console.log(instance.subPublicMethod());
// 预期输出值:"hello world"
```
@@ -296,21 +300,21 @@ console.log(instance.subPublicMethod())
```js
class ClassWithGetSet {
- #msg = 'hello world'
+ #msg = "hello world";
get msg() {
- return this.#msg
+ return this.#msg;
}
set msg(x) {
- this.#msg = `hello ${x}`
- }
+ this.#msg = `hello ${x}`;
+ }
}
-const instance = new ClassWithGetSet()
-console.log(instance.msg)
+const instance = new ClassWithGetSet();
+console.log(instance.msg);
// 预期输出值:"hello world"
-instance.msg = 'cake'
-console.log(instance.msg)
+instance.msg = "cake";
+console.log(instance.msg);
// 预期输出值:"hello cake"
```
diff --git a/files/zh-cn/web/javascript/reference/classes/static/index.md b/files/zh-cn/web/javascript/reference/classes/static/index.md
index 403106eb068c1f..0961f9546388e1 100644
--- a/files/zh-cn/web/javascript/reference/classes/static/index.md
+++ b/files/zh-cn/web/javascript/reference/classes/static/index.md
@@ -27,12 +27,12 @@ static methodName() { ... }
```js
class StaticMethodCall {
- static staticMethod() {
- return 'Static method has been called';
- }
- static anotherStaticMethod() {
- return this.staticMethod() + ' from another static method';
- }
+ static staticMethod() {
+ return "Static method has been called";
+ }
+ static anotherStaticMethod() {
+ return this.staticMethod() + " from another static method";
+ }
}
StaticMethodCall.staticMethod();
// 'Static method has been called'
@@ -47,15 +47,15 @@ StaticMethodCall.anotherStaticMethod();
```js
class StaticMethodCall {
- constructor() {
- console.log(StaticMethodCall.staticMethod());
- // 'static method has been called.'
- console.log(this.constructor.staticMethod());
- // 'static method has been called.'
- }
- static staticMethod() {
- return 'static method has been called.';
- }
+ constructor() {
+ console.log(StaticMethodCall.staticMethod());
+ // 'static method has been called.'
+ console.log(this.constructor.staticMethod());
+ // 'static method has been called.'
+ }
+ static staticMethod() {
+ return "static method has been called.";
+ }
}
```
@@ -74,21 +74,19 @@ class Tripple {
}
}
-
class BiggerTripple extends Tripple {
static tripple(n) {
return super.tripple(n) * super.tripple(n);
}
}
-
-console.log(Tripple.tripple());// 3
-console.log(Tripple.tripple(6));// 18
+console.log(Tripple.tripple()); // 3
+console.log(Tripple.tripple(6)); // 18
let tp = new Tripple();
-console.log(BiggerTripple.tripple(3));// 81(不会受父类实例化的影响)
-console.log(tp.tripple());// 'tp.tripple 不是一个函数'.
+console.log(BiggerTripple.tripple(3)); // 81(不会受父类实例化的影响)
+console.log(tp.tripple()); // 'tp.tripple 不是一个函数'.
```
## 规范
diff --git a/files/zh-cn/web/javascript/reference/deprecated_and_obsolete_features/index.md b/files/zh-cn/web/javascript/reference/deprecated_and_obsolete_features/index.md
index 73a4306fae5c04..7c99a5002e59d2 100644
--- a/files/zh-cn/web/javascript/reference/deprecated_and_obsolete_features/index.md
+++ b/files/zh-cn/web/javascript/reference/deprecated_and_obsolete_features/index.md
@@ -99,11 +99,11 @@ console.log("b");
以下是 `RegExp` 实例的属性,不再是 `RegExp` 构造函数的属性:
| 属性 | 描述 |
-|---------------------------------------------------------------------|----------------------------------------------------------------------------------|
-| {{jsxref("RegExp/global", "global")}} | 是否针对字符串中所有可能的匹配进行正则表达式测试,或者只针对第一个匹配进行测试。 |
-| {{jsxref("RegExp/ignoreCase", "ignoreCase")}} | 在尝试匹配一个字符串时是否忽略大小写。 |
-| {{jsxref("RegExp/lastIndex", "lastIndex")}} | 开始下一次匹配的索引。 |
-| {{jsxref("RegExp/multiline", "multiline")}}(也可通过 `RegExp.$*`) | 是否在多行的字符串中搜索。 |
+| ------------------------------------------------------------------- | -------------------------------------------------------------------------------- |
+| {{jsxref("RegExp/global", "global")}} | 是否针对字符串中所有可能的匹配进行正则表达式测试,或者只针对第一个匹配进行测试。 |
+| {{jsxref("RegExp/ignoreCase", "ignoreCase")}} | 在尝试匹配一个字符串时是否忽略大小写。 |
+| {{jsxref("RegExp/lastIndex", "lastIndex")}} | 开始下一次匹配的索引。 |
+| {{jsxref("RegExp/multiline", "multiline")}}(也可通过 `RegExp.$*`) | 是否在多行的字符串中搜索。 |
| {{jsxref("RegExp/source", "source")}} | 模式的文本。 |
`valueOf()` 方法不再专门用于 `RegExp`。它使用 {{jsxref("Object.prototype.valueOf()")}},并返回它本身。
@@ -115,7 +115,7 @@ console.log("b");
### Object
| 属性 | 描述 | 替代方法 |
-|------------------------------|----------------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------|
+| ---------------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `__count__` | 返回直接在用户定义的对象上的可枚举属性的数量。 | [`Object.keys()`](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/keys) |
| `__parent__` | 指向对象的上下文 | 没有直接的替换方法 |
| `__iterator__` | 和[遗留的生成器和迭代器](#遗留的生成器和迭代器)一起使用。 | [`Symbol.iterator`](/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Symbol/iterator) 和新的[迭代协议](/zh-CN/docs/Web/JavaScript/Reference/Iteration_protocols) |
@@ -124,8 +124,8 @@ console.log("b");
| `Object.observe()` | 异步地观察一个对象的变化。 | {{jsxref("Proxy")}} |
| `Object.unobserve()` | 移除观察器。 | {{jsxref("Proxy")}} |
| `Object.getNotifier()` | 创建一个通知者对象,允许用 `Object.observe()` 来综合触发一个变化的观察者。 | 没有直接的替换方法 |
-| `Object.prototype.watch()` | 在一个属性上附加一个处理器回调,当属性被分配时被调用。 | {{jsxref("Proxy")}} |
-| `Object.prototype.unwatch()` | 移除一个属性上的观察处理器。 | {{jsxref("Proxy")}} |
+| `Object.prototype.watch()` | 在一个属性上附加一个处理器回调,当属性被分配时被调用。 | {{jsxref("Proxy")}} |
+| `Object.prototype.unwatch()` | 移除一个属性上的观察处理器。 | {{jsxref("Proxy")}} |
### String
@@ -146,7 +146,7 @@ console.log("b");
非标准的 Array 通用方法,如 `Array.slice(myArr, 0, 12)`、`Array.forEach(myArr, myFn)` 等,在 Firefox 1.5(JavaScript 1.6)中引入,在 Firefox 68 中被废弃,并在 Firefox 71 中删除。你可以使用 {{jsxref("Array", "Array.prototype", "实例方法")}} 和 {{jsxref("Function.call")}} 来代替。
| 属性 | 描述 | 替代 |
-|---------------------|----------------------|---------------------|
+| ------------------- | -------------------- | ------------------- |
| `Array.observe()` | 异步地观察数组的变化 | {{jsxref("Proxy")}} |
| `Array.unobserve()` | 移除观察器。 | {{jsxref("Proxy")}} |
diff --git a/files/zh-cn/web/javascript/reference/errors/already_has_pragma/index.md b/files/zh-cn/web/javascript/reference/errors/already_has_pragma/index.md
index aab963b770de92..b04e74da2b14d5 100644
--- a/files/zh-cn/web/javascript/reference/errors/already_has_pragma/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/already_has_pragma/index.md
@@ -1,5 +1,5 @@
---
-title: 'Warning: -file- is being assigned a //# sourceMappingURL, but already has one'
+title: "Warning: -file- is being assigned a //# sourceMappingURL, but already has one"
slug: Web/JavaScript/Reference/Errors/Already_has_pragma
---
diff --git a/files/zh-cn/web/javascript/reference/errors/array_sort_argument/index.md b/files/zh-cn/web/javascript/reference/errors/array_sort_argument/index.md
index 74c1bbf7e8fa5d..50c0508159e88f 100644
--- a/files/zh-cn/web/javascript/reference/errors/array_sort_argument/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/array_sort_argument/index.md
@@ -1,5 +1,5 @@
---
-title: 'TypeError: invalid Array.prototype.sort argument'
+title: "TypeError: invalid Array.prototype.sort argument"
slug: Web/JavaScript/Reference/Errors/Array_sort_argument
---
@@ -24,20 +24,19 @@ TypeError: invalid Array.prototype.sort argument (Firefox)
### 无效的
```js example-bad
-[1, 3, 2].sort(5); // TypeError
+[1, 3, 2].sort(5); // TypeError
-var cmp = { asc: (x, y) => x >= y, dsc : (x, y) => x <= y };
-[1, 3, 2].sort(cmp[this.key] || 'asc'); // TypeError
+var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y };
+[1, 3, 2].sort(cmp[this.key] || "asc"); // TypeError
```
### 有效的
```js example-good
-[1, 3, 2].sort(); // [1, 2, 3]
+[1, 3, 2].sort(); // [1, 2, 3]
-
-var cmp = { asc: (x, y) => x >= y, dsc : (x, y) => x <= y };
-[1, 3, 2].sort(cmp[this.key || 'asc']); // [1, 2, 3]
+var cmp = { asc: (x, y) => x >= y, dsc: (x, y) => x <= y };
+[1, 3, 2].sort(cmp[this.key || "asc"]); // [1, 2, 3]
```
## 相关
diff --git a/files/zh-cn/web/javascript/reference/errors/bad_radix/index.md b/files/zh-cn/web/javascript/reference/errors/bad_radix/index.md
index d9f5766657d8e7..7590cacfb16805 100644
--- a/files/zh-cn/web/javascript/reference/errors/bad_radix/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/bad_radix/index.md
@@ -1,5 +1,5 @@
---
-title: 'RangeError: radix must be an integer'
+title: "RangeError: radix must be an integer"
slug: Web/JavaScript/Reference/Errors/Bad_radix
---
@@ -45,10 +45,10 @@ RangeError: toString() radix argument must be between 2 and 36 (Chrome)
### 正确示例
```js example-good
-(42).toString(2); // "101010" (binary)
-(13).toString(8); // "15" (octal)
-(0x42).toString(10); // "66" (decimal)
-(100000).toString(16) // "186a0" (hexadecimal)
+(42).toString(2); // "101010" (binary)
+(13).toString(8); // "15" (octal)
+(0x42).toString(10); // "66" (decimal)
+(100000).toString(16); // "186a0" (hexadecimal)
```
## 参考
diff --git a/files/zh-cn/web/javascript/reference/errors/bad_regexp_flag/index.md b/files/zh-cn/web/javascript/reference/errors/bad_regexp_flag/index.md
index 49de9a1f0c1883..a90f204e1bb2dc 100644
--- a/files/zh-cn/web/javascript/reference/errors/bad_regexp_flag/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/bad_regexp_flag/index.md
@@ -29,15 +29,15 @@ var re = /pattern/flags;
或
```js
-var re = new RegExp('pattern', 'flags');
+var re = new RegExp("pattern", "flags");
```
-| 标记 | 说明 |
-| ---- | ------------------------------------------------------------------------------------------------- |
-| `g` | 整体检索。 |
-| i | 忽略大小写检索。 |
-| m | 多行检索。 |
-| u | Unicode; 将模式视为 Unicode 码点的序列 |
+| 标记 | 说明 |
+| ---- | -------------------------------------------------------------------------------------- |
+| `g` | 整体检索。 |
+| i | 忽略大小写检索。 |
+| m | 多行检索。 |
+| u | Unicode; 将模式视为 Unicode 码点的序列 |
| y | sticky 检索将从目标字符串的当前位置开始匹配。参阅{{jsxref("RegExp.sticky", "sticky")}} |
## 示例
@@ -64,7 +64,7 @@ let obj = {
```js example-good
let obj = {
- url: '/docs/Web'
+ url: "/docs/Web",
};
```
diff --git a/files/zh-cn/web/javascript/reference/errors/bad_return/index.md b/files/zh-cn/web/javascript/reference/errors/bad_return/index.md
index e571a99e4dd4bd..ec87c19e3c389e 100644
--- a/files/zh-cn/web/javascript/reference/errors/bad_return/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/bad_return/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: return not in function'
+title: "SyntaxError: return not in function"
slug: Web/JavaScript/Reference/Errors/Bad_return
original_slug: Web/JavaScript/Reference/Errors/Bad_return_or_yield
---
@@ -40,7 +40,7 @@ var cheer = function(score) {
初次看好像没什么错误,但是上面这段代码在第一个 if 后面少了一个“ { ”。正确的应该如下:
```js example-good
-var cheer = function(score) {
+var cheer = function (score) {
if (score === 147) {
return "Maximum!";
}
diff --git a/files/zh-cn/web/javascript/reference/errors/called_on_incompatible_type/index.md b/files/zh-cn/web/javascript/reference/errors/called_on_incompatible_type/index.md
index 1bb54052616da9..94b5f5037a1e60 100644
--- a/files/zh-cn/web/javascript/reference/errors/called_on_incompatible_type/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/called_on_incompatible_type/index.md
@@ -31,24 +31,24 @@ TypeError: Bind must be called on a function (Chrome)
### 错误示例
```js example-bad
-var mySet = new Set;
-['bar', 'baz'].forEach(mySet.add);
+var mySet = new Set();
+["bar", "baz"].forEach(mySet.add);
// mySet.add is a function, but "mySet" is not captured as this.
var myFun = function () {};
-['bar', 'baz'].forEach(myFun.bind);
+["bar", "baz"].forEach(myFun.bind);
// myFun.bind is a function, but "myFun" is not captured as this.
```
### 正确示例
```js example-good
-var mySet = new Set;
-['bar', 'baz'].forEach(mySet.add.bind(mySet));
+var mySet = new Set();
+["bar", "baz"].forEach(mySet.add.bind(mySet));
// This works due to binding "mySet" as this.
var myFun = function () {};
-['bar', 'baz'].forEach(x => myFun.bind(x));
+["bar", "baz"].forEach((x) => myFun.bind(x));
// This works using the "bind" function. It creates a lambda forwarding the argument.
```
diff --git a/files/zh-cn/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.md b/files/zh-cn/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.md
index dd0cb13bcd33e2..f839e2882bde5e 100644
--- a/files/zh-cn/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/cant_access_lexical_declaration_before_init/index.md
@@ -1,5 +1,5 @@
---
-title: 'ReferenceError: can''t access lexical declaration`X'' before initialization'
+title: "ReferenceError: can't access lexical declaration`X' before initialization"
slug: Web/JavaScript/Reference/Errors/Cant_access_lexical_declaration_before_init
---
@@ -26,11 +26,11 @@ ReferenceError: assignment to undeclared variable "x" (Firefox)
在这个例子中,变量 "foo" 在语句块中再次声明,导致未初始化。
```js example-bad
-function test(){
- let foo = 33;
- if (true) {
- let foo = (foo + 55); // ReferenceError: can't access lexical declaration `foo' before initialization
- }
+function test() {
+ let foo = 33;
+ if (true) {
+ let foo = foo + 55; // ReferenceError: can't access lexical declaration `foo' before initialization
+ }
}
test();
```
@@ -40,11 +40,11 @@ test();
在 if 语句块中修改变量 "foo" 的值,不应该在其中进行二次声明。
```js example-good
-function test(){
- let foo = 33;
- if (true) {
- foo = (foo + 55);
- }
+function test() {
+ let foo = 33;
+ if (true) {
+ foo = foo + 55;
+ }
}
test();
```
diff --git a/files/zh-cn/web/javascript/reference/errors/cant_assign_to_property/index.md b/files/zh-cn/web/javascript/reference/errors/cant_assign_to_property/index.md
index f0b78f9746a283..64dc18a83f1c5c 100644
--- a/files/zh-cn/web/javascript/reference/errors/cant_assign_to_property/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/cant_assign_to_property/index.md
@@ -28,7 +28,7 @@ TypeError: Cannot create property 'x' on {y} (Chrome)
### 错误的情况
```js example-bad
-'use strict';
+"use strict";
var foo = "my string";
// 下面这行代码在非严格模式下不会执行。
@@ -40,7 +40,7 @@ foo.bar = {}; // TypeError: can't assign to property "bar" on "my string": not a
有两种方式,第一种修复这部分代码阻止{{Glossary("primitive")}}被用于这种情况,或者可以通过使用对象构造器创建来修复。
```js example-good
-'use strict';
+"use strict";
var foo = new String("my string");
foo.bar = {};
diff --git a/files/zh-cn/web/javascript/reference/errors/cant_define_property_object_not_extensible/index.md b/files/zh-cn/web/javascript/reference/errors/cant_define_property_object_not_extensible/index.md
index 88c6e94a4d08d4..f19276ddc9c392 100644
--- a/files/zh-cn/web/javascript/reference/errors/cant_define_property_object_not_extensible/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/cant_define_property_object_not_extensible/index.md
@@ -25,34 +25,32 @@ TypeError: Cannot define property: "x", object is not extensible. (Chrome)
在[严格模式](/zh-CN/docs/Web/JavaScript/Reference/Strict_mode)下,向已经标记为不可扩展的对象添加新属性会报 TypeError 错误。而在非严格模式下,添加属性“x”会被静默忽略。
```js example-bad
-'use strict';
+"use strict";
var obj = {};
Object.preventExtensions(obj);
-obj.x = 'foo';
+obj.x = "foo";
// TypeError: can't define property "x": "obj" is not extensible
```
在[严格模式](/zh-CN/docs/Web/JavaScript/Reference/Strict_mode)和非严格模式下两种模式下,调用{{jsxref("Object.defineProperty()")}} 向标记为不可扩展的对象添加新属性都会报 TypeError 错误。
```js example-bad
-var obj = { };
+var obj = {};
Object.preventExtensions(obj);
-Object.defineProperty(obj,
- 'x', { value: "foo" }
-);
+Object.defineProperty(obj, "x", { value: "foo" });
// TypeError: can't define property "x": "obj" is not extensible
```
为了修复这个错误,你可以彻底移除 {{jsxref("Object.preventExtensions()")}} 语句,或者将其移动位置,使得属性在对象被标记为不可扩展之前添加。当然如果不需要试图添加的属性的话,你也可以将其移除。
```js example-good
-'use strict';
+"use strict";
var obj = {};
-obj.x = 'foo'; // add property first and only then prevent extensions
+obj.x = "foo"; // add property first and only then prevent extensions
Object.preventExtensions(obj);
```
diff --git a/files/zh-cn/web/javascript/reference/errors/cant_delete/index.md b/files/zh-cn/web/javascript/reference/errors/cant_delete/index.md
index bbbbe6ebbd3697..efb07688c70da7 100644
--- a/files/zh-cn/web/javascript/reference/errors/cant_delete/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/cant_delete/index.md
@@ -27,25 +27,25 @@ TypeError: Cannot delete property 'x' of #
(Chrome)
不可配置的属性并不特别常见,但是它们可以使用 {{jsxref("Object.defineProperty()")}} 或 {{jsxref("Object.freeze()")}} 创建。
```js example-bad
-'use strict';
-var obj = Object.freeze({name: 'Elsa', score: 157});
-delete obj.score; // TypeError
+"use strict";
+var obj = Object.freeze({ name: "Elsa", score: 157 });
+delete obj.score; // TypeError
-'use strict';
+("use strict");
var obj = {};
-Object.defineProperty(obj, 'foo', {value: 2, configurable: false});
-delete obj.foo; // TypeError
+Object.defineProperty(obj, "foo", { value: 2, configurable: false });
+delete obj.foo; // TypeError
-'use strict';
+("use strict");
var frozenArray = Object.freeze([0, 1, 2]);
-frozenArray.pop(); // TypeError
+frozenArray.pop(); // TypeError
```
也有一些内建于 JavaScript 的不可配置属性。你可能会尝试删除一个数学常量。
```js example-bad
-'use strict';
-delete Math.PI; // TypeError
+"use strict";
+delete Math.PI; // TypeError
```
## 另见
diff --git a/files/zh-cn/web/javascript/reference/errors/cant_redefine_property/index.md b/files/zh-cn/web/javascript/reference/errors/cant_redefine_property/index.md
index 8f3845146b056d..c12d213091eb28 100644
--- a/files/zh-cn/web/javascript/reference/errors/cant_redefine_property/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/cant_redefine_property/index.md
@@ -28,9 +28,9 @@ TypeError: Cannot redefine property: "x" (Chrome)
```js example-bad
var obj = Object.create({});
-Object.defineProperty(obj, "foo", {value: "bar"});
+Object.defineProperty(obj, "foo", { value: "bar" });
-Object.defineProperty(obj, "foo", {value: "baz"});
+Object.defineProperty(obj, "foo", { value: "baz" });
// TypeError: can't redefine non-configurable property "foo"
```
@@ -38,8 +38,8 @@ Object.defineProperty(obj, "foo", {value: "baz"});
```js example-good
var obj = Object.create({});
-Object.defineProperty(obj, "foo", {value: "bar", configurable: true});
-Object.defineProperty(obj, "foo", {value: "baz", configurable: true});
+Object.defineProperty(obj, "foo", { value: "bar", configurable: true });
+Object.defineProperty(obj, "foo", { value: "baz", configurable: true });
```
## 参见
diff --git a/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.md b/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.md
index e4131529ec4e6a..135b6c49b547a2 100644
--- a/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/cyclic_object_value/index.md
@@ -1,5 +1,5 @@
---
-title: 'TypeError: cyclic object value'
+title: "TypeError: cyclic object value"
slug: Web/JavaScript/Reference/Errors/Cyclic_object_value
---
@@ -49,7 +49,7 @@ JSON.stringify(circularReference);
const getCircularReplacer = () => {
const seen = new WeakSet();
return (key, value) => {
- if (typeof value === 'object' && value !== null) {
+ if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return;
}
diff --git a/files/zh-cn/web/javascript/reference/errors/delete_in_strict_mode/index.md b/files/zh-cn/web/javascript/reference/errors/delete_in_strict_mode/index.md
index 086330c7325c2f..6c6e71a28a5215 100644
--- a/files/zh-cn/web/javascript/reference/errors/delete_in_strict_mode/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/delete_in_strict_mode/index.md
@@ -33,7 +33,7 @@ delete 操作符只能用于删除对象中的属性。只有可配置的对象
在 JavaScript 中,普通变量是不能删除的,在严格模式下会报错:
```js example-bad
-'use strict';
+"use strict";
var x;
@@ -48,7 +48,7 @@ delete x;
要释放变量引用的内容,可以将变量值设置为 {{jsxref("null")}}:
```js example-good
-'use strict';
+"use strict";
var x;
diff --git a/files/zh-cn/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.md b/files/zh-cn/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.md
index 33deadf4c9e2fe..1c5647c45592ea 100644
--- a/files/zh-cn/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/deprecated_caller_or_arguments_usage/index.md
@@ -1,5 +1,5 @@
---
-title: 'ReferenceError: deprecated caller or arguments usage'
+title: "ReferenceError: deprecated caller or arguments usage"
slug: Web/JavaScript/Reference/Errors/Deprecated_caller_or_arguments_usage
---
@@ -32,9 +32,9 @@ TypeError: 'callee' and 'caller' cannot be accessed in strict mode. (Safari)
function myFunc() {
if (myFunc.caller == null) {
- return 'The function was called from the top!';
+ return "The function was called from the top!";
} else {
- return 'This function\'s caller was ' + myFunc.caller;
+ return "This function's caller was " + myFunc.caller;
}
}
@@ -50,17 +50,21 @@ myFunc();
```js example-bad
"use strict";
-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('returned: ' + g.arguments);
+console.log("returned: " + g.arguments);
// Warning: ReferenceError: deprecated arguments usage
```
diff --git a/files/zh-cn/web/javascript/reference/errors/deprecated_octal/index.md b/files/zh-cn/web/javascript/reference/errors/deprecated_octal/index.md
index 7d8dddb4edb7ac..072c2019f823a0 100644
--- a/files/zh-cn/web/javascript/reference/errors/deprecated_octal/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/deprecated_octal/index.md
@@ -56,7 +56,7 @@ for octal literals use the \"0o\" prefix instead
至于八进制转义序列,你可以使用十六进制转义序列来代替:
```js example-good
-'\xA9';
+"\xA9";
```
## 参见
diff --git a/files/zh-cn/web/javascript/reference/errors/equal_as_assign/index.md b/files/zh-cn/web/javascript/reference/errors/equal_as_assign/index.md
index cf7c08504d7683..20d07acaf719bf 100644
--- a/files/zh-cn/web/javascript/reference/errors/equal_as_assign/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/equal_as_assign/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: test for equality (==) mistyped as assignment (=)?'
+title: "SyntaxError: test for equality (==) mistyped as assignment (=)?"
slug: Web/JavaScript/Reference/Errors/Equal_as_assign
---
@@ -25,7 +25,7 @@ Warning: SyntaxError: test for equality (==) mistyped as assignment (=)?
不建议在条件表达式中(例如 [`if...else`](/zh-CN/docs/Web/JavaScript/Reference/Statements/if...else))使用简单赋值语句,因为在扫视代码的时候赋值操作与相等判定容易产生混淆。例如,不要使用以下写法:
-```js example-bad
+```js-nolint example-bad
if (x = y) {
// do the right thing
}
diff --git a/files/zh-cn/web/javascript/reference/errors/getter_only/index.md b/files/zh-cn/web/javascript/reference/errors/getter_only/index.md
index f0f24c81d6cc1b..a0c1c01b50e871 100644
--- a/files/zh-cn/web/javascript/reference/errors/getter_only/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/getter_only/index.md
@@ -29,11 +29,11 @@ TypeError: Cannot set property "prop" of # which has only a getter (Chro
function Archiver() {
var temperature = null;
- Object.defineProperty(this, 'temperature', {
- get: function() {
- console.log('get!');
+ Object.defineProperty(this, "temperature", {
+ get: function () {
+ console.log("get!");
return temperature;
- }
+ },
});
}
@@ -53,18 +53,20 @@ function Archiver() {
var temperature = null;
var archive = [];
- Object.defineProperty(this, 'temperature', {
- get: function() {
- console.log('get!');
+ Object.defineProperty(this, "temperature", {
+ get: function () {
+ console.log("get!");
return temperature;
},
- set: function(value) {
+ set: function (value) {
temperature = value;
archive.push({ val: temperature });
- }
+ },
});
- this.getArchive = function() { return archive; };
+ this.getArchive = function () {
+ return archive;
+ };
}
var arc = new Archiver();
diff --git a/files/zh-cn/web/javascript/reference/errors/identifier_after_number/index.md b/files/zh-cn/web/javascript/reference/errors/identifier_after_number/index.md
index dae759f8ecaa4a..3cb44dec1dba8a 100644
--- a/files/zh-cn/web/javascript/reference/errors/identifier_after_number/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/identifier_after_number/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: identifier starts immediately after numeric literal'
+title: "SyntaxError: identifier starts immediately after numeric literal"
slug: Web/JavaScript/Reference/Errors/Identifier_after_number
---
@@ -39,7 +39,7 @@ var foo = 1life;
You will need to rename your variable to avoid the leading number.
```js example-good
-var life1 = 'foo';
+var life1 = "foo";
var foo = life1;
```
diff --git a/files/zh-cn/web/javascript/reference/errors/illegal_character/index.md b/files/zh-cn/web/javascript/reference/errors/illegal_character/index.md
index eb3c8d2012162c..7dcd41d1c3de47 100644
--- a/files/zh-cn/web/javascript/reference/errors/illegal_character/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/illegal_character/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: illegal character'
+title: "SyntaxError: illegal character"
slug: Web/JavaScript/Reference/Errors/Illegal_character
---
@@ -18,7 +18,7 @@ SyntaxError: Invalid or unexpected token (Chrome)
## 哪里出错了?
-在代码中有非法的或者不期望出现的标记符号出现在不该出现的位置。请使用支持语法高亮功能的编辑器仔细检查你的代码,看看是否存在张冠李戴的情况,比如减号 (` - `) 与连接符 (` – `) ,或者是英文双引号 (` " `) 与中文双引号 (` “ `)。
+在代码中有非法的或者不期望出现的标记符号出现在不该出现的位置。请使用支持语法高亮功能的编辑器仔细检查你的代码,看看是否存在张冠李戴的情况,比如减号 (`-`) 与连接符 (`–`) ,或者是英文双引号 (`"`) 与中文双引号 (`“`)。
## 示例
@@ -54,7 +54,7 @@ var colors = ['#000', #333', '#666'];
把遗漏的引号给 '#333' 添加上。
```js example-good
-var colors = ['#000', '#333', '#666'];
+var colors = ["#000", "#333", "#666"];
```
### 隐藏字符
diff --git a/files/zh-cn/web/javascript/reference/errors/in_operator_no_object/index.md b/files/zh-cn/web/javascript/reference/errors/in_operator_no_object/index.md
index 39d3973ba3fd67..ea59c277bf1208 100644
--- a/files/zh-cn/web/javascript/reference/errors/in_operator_no_object/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/in_operator_no_object/index.md
@@ -63,7 +63,7 @@ var foo = { baz: "bar" };
当使用 in 操作符来对 {{jsxref("Array")}} 对象进行检索的时候一定要特别小心,因为它检测的是索引值而不是位于索引位置的值。
```js
-var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
+var trees = ["redwood", "bay", "cedar", "oak", "maple"];
3 in trees; // true
"oak" in trees; // false
```
diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_array_length/index.md b/files/zh-cn/web/javascript/reference/errors/invalid_array_length/index.md
index 9a4df5a72e7e04..8fd53c226b094e 100644
--- a/files/zh-cn/web/javascript/reference/errors/invalid_array_length/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/invalid_array_length/index.md
@@ -1,5 +1,5 @@
---
-title: 'RangeError: invalid array length'
+title: "RangeError: invalid array length"
slug: Web/JavaScript/Reference/Errors/Invalid_array_length
---
@@ -35,25 +35,25 @@ RangeError: Invalid array buffer length (Chrome)
### 错误的示例
```js example-bad
-new Array(Math.pow(2, 40))
-new Array(-1)
-new ArrayBuffer(Math.pow(2, 32))
-new ArrayBuffer(-1)
+new Array(Math.pow(2, 40));
+new Array(-1);
+new ArrayBuffer(Math.pow(2, 32));
+new ArrayBuffer(-1);
let a = [];
-a.length = a.length - 1; // 将 length 属性的值设置为 -1
+a.length = a.length - 1; // 将 length 属性的值设置为 -1
let b = new Array(Math.pow(2, 32) - 1);
-b.length = b.length + 1; // 将 length 属性的值设置为 2^32
+b.length = b.length + 1; // 将 length 属性的值设置为 2^32
```
### 正确的示例
```js example-good
-[ Math.pow(2, 40) ] // [ 1099511627776 ]
-[ -1 ] // [ -1 ]
-new ArrayBuffer(Math.pow(2, 32) - 1)
-new ArrayBuffer(0)
+[ Math.pow(2, 40) ]; // [ 1099511627776 ]
+[ -1 ]; // [ -1 ]
+new ArrayBuffer(Math.pow(2, 32) - 1);
+new ArrayBuffer(0);
let a = [];
a.length = Math.max(0, a.length - 1);
diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.md b/files/zh-cn/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.md
index fac0deff600755..4413d7a9bf6d91 100644
--- a/files/zh-cn/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/invalid_assignment_left-hand_side/index.md
@@ -1,5 +1,5 @@
---
-title: 'ReferenceError: invalid assignment left-hand side'
+title: "ReferenceError: invalid assignment left-hand side"
slug: Web/JavaScript/Reference/Errors/Invalid_assignment_left-hand_side
---
@@ -37,12 +37,10 @@ var str = 'Hello, '
```js example-good
if (Math.PI == 3 || Math.PI == 4) {
- console.log('no way!');
+ console.log("no way!");
}
-var str = 'Hello, '
-+ 'from the '
-+ 'other side!';
+var str = "Hello, " + "from the " + "other side!";
```
## See also
diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_const_assignment/index.md b/files/zh-cn/web/javascript/reference/errors/invalid_const_assignment/index.md
index fadca1b50d2e1e..018f407be9d681 100644
--- a/files/zh-cn/web/javascript/reference/errors/invalid_const_assignment/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/invalid_const_assignment/index.md
@@ -77,14 +77,14 @@ function setupBigScreenEnvironment() {
const 声明语句创建了一个对值的只读引用。这并**不**意味着它指向的值是不可变的,而是说这个变量标记符不能被再次分配。例如,在值是对象的情况下,引用的对象自身内容依然是可以改变的。不能改变该变量的引用:
```js example-bad
-const obj = {foo: 'bar'};
-obj = {foo: 'baz'}; // TypeError: invalid assignment to const `obj'
+const obj = { foo: "bar" };
+obj = { foo: "baz" }; // TypeError: invalid assignment to const `obj'
```
但是可以改变它引用的值的属性:
```js example-good
-obj.foo = 'baz';
+obj.foo = "baz";
obj; // Object { foo: "baz" }
```
diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_date/index.md b/files/zh-cn/web/javascript/reference/errors/invalid_date/index.md
index 6a379d9cd7c25c..d8b74f013b2525 100644
--- a/files/zh-cn/web/javascript/reference/errors/invalid_date/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/invalid_date/index.md
@@ -1,5 +1,5 @@
---
-title: 'RangeError: invalid date'
+title: "RangeError: invalid date"
slug: Web/JavaScript/Reference/Errors/Invalid_date
---
@@ -28,15 +28,15 @@ slug: Web/JavaScript/Reference/Errors/Invalid_date
ISO 格式化字符串中不可识别的字符串或者包含非法元素值的日期一般会返回 {{jsxref("NaN")}}。然而,根据实现的不同,不符合 ISO 格式的字符串可能也会抛出 `RangeError: invalid date`,比如在火狐浏览器中有以下情形:
```js example-bad
-new Date('foo-bar 2014');
-new Date('2014-25-23').toISOString();
-new Date('foo-bar 2014').toString();
+new Date("foo-bar 2014");
+new Date("2014-25-23").toISOString();
+new Date("foo-bar 2014").toString();
```
然而下面这种情形会返回 {{jsxref("NaN")}} :
```js example-bad
-Date.parse('foo-bar 2014'); // NaN
+Date.parse("foo-bar 2014"); // NaN
```
参见 {{jsxref("Date.parse()")}} 文档,了解更多详情。
@@ -44,7 +44,7 @@ Date.parse('foo-bar 2014'); // NaN
### 正确示例
```js example-good
-new Date('05 October 2011 14:48 UTC');
+new Date("05 October 2011 14:48 UTC");
```
## 另见
diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_for-in_initializer/index.md b/files/zh-cn/web/javascript/reference/errors/invalid_for-in_initializer/index.md
index 9b3d6160ff0ef6..573ffd6e2f36be 100644
--- a/files/zh-cn/web/javascript/reference/errors/invalid_for-in_initializer/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/invalid_for-in_initializer/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: for-in loop head declarations may not have initializers'
+title: "SyntaxError: for-in loop head declarations may not have initializers"
slug: Web/JavaScript/Reference/Errors/Invalid_for-in_initializer
---
@@ -44,7 +44,7 @@ for (var i = 0 in obj) {
```js example-good
"use strict";
-var obj = {a: 1, b: 2, c: 3 };
+var obj = { a: 1, b: 2, c: 3 };
for (var i in obj) {
console.log(obj[i]);
@@ -56,7 +56,7 @@ for (var i in obj) {
for...in 循环[不应该应用于数组迭代中](/zh-CN/docs/Web/JavaScript/Reference/Statements/for...in#Array_iteration_and_for...in)。是否考虑使用 [`for`](/zh-CN/docs/Web/JavaScript/Reference/Statements/for) 循环而不是 `for-in` 循环来遍历数组({{jsxref("Array")}})?在 for 循环中是允许使用初始化语句的:
```js example-good
-var arr = [ "a", "b", "c" ]
+var arr = ["a", "b", "c"];
for (var i = 2; i < arr.length; i++) {
console.log(arr[i]);
diff --git a/files/zh-cn/web/javascript/reference/errors/invalid_right_hand_side_instanceof_operand/index.md b/files/zh-cn/web/javascript/reference/errors/invalid_right_hand_side_instanceof_operand/index.md
index 54c56176cb35ae..7729719987d8b3 100644
--- a/files/zh-cn/web/javascript/reference/errors/invalid_right_hand_side_instanceof_operand/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/invalid_right_hand_side_instanceof_operand/index.md
@@ -1,5 +1,5 @@
---
-title: 'TypeError: invalid ''instanceof'' operand ''x'''
+title: "TypeError: invalid 'instanceof' operand 'x'"
slug: Web/JavaScript/Reference/Errors/invalid_right_hand_side_instanceof_operand
---
@@ -26,28 +26,28 @@ TypeError: Right-hand side of 'instanceof' is not callable (Chrome)
```js example-bad
"test" instanceof ""; // TypeError: invalid 'instanceof' operand ""
-42 instanceof 0; // TypeError: invalid 'instanceof' operand 0
+42 instanceof 0; // TypeError: invalid 'instanceof' operand 0
function Foo() {}
-var f = Foo(); // Foo() is called and returns undefined
+var f = Foo(); // Foo() is called and returns undefined
var x = new Foo();
-x instanceof f; // TypeError: invalid 'instanceof' operand f
-x instanceof x; // TypeError: x is not a function
+x instanceof f; // TypeError: invalid 'instanceof' operand f
+x instanceof x; // TypeError: x is not a function
```
为了解决上述问题,你可能需要将[`instanceof` 操作符](/zh-CN/docs/Web/JavaScript/Reference/Operators/instanceof) 换成 [`typeof` 操作符](/zh-CN/docs/Web/JavaScript/Reference/Operators/typeof),或者确保你使用的是函数名称,而不是函数计算的结果。
```js example-good
typeof "test" == "string"; // true
-typeof 42 == "number" // true
+typeof 42 == "number"; // true
function Foo() {}
-var f = Foo; // Do not call Foo.
+var f = Foo; // Do not call Foo.
var x = new Foo();
-x instanceof f; // true
-x instanceof Foo; // true
+x instanceof f; // true
+x instanceof Foo; // true
```
## 参见
diff --git a/files/zh-cn/web/javascript/reference/errors/is_not_iterable/index.md b/files/zh-cn/web/javascript/reference/errors/is_not_iterable/index.md
index 4e5138b13150d5..6e7e13adb1d831 100644
--- a/files/zh-cn/web/javascript/reference/errors/is_not_iterable/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/is_not_iterable/index.md
@@ -1,5 +1,5 @@
---
-title: 'TypeError: ''x'' is not iterable'
+title: "TypeError: 'x' is not iterable"
slug: Web/JavaScript/Reference/Errors/is_not_iterable
---
@@ -27,43 +27,42 @@ TypeError: 'x' is not a function or its return value is not iterable (Chrome)
在 JavaScript 中,{{jsxref("Object")}} 是不可迭代的,除非它们实现了[迭代协议](/zh-CN/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol). 因此,你不能使用 [for…of](/zh-CN/docs/Web/JavaScript/Guide/Loops_and_iteration#for...of_statement) 来迭代对象的属性。
```js example-bad
-var obj = { 'France': 'Paris', 'England': 'London' };
-for (let p of obj) { // TypeError: obj is not iterable
- // …
+var obj = { France: "Paris", England: "London" };
+for (let p of obj) {
+ // TypeError: obj is not iterable
+ // …
}
```
做为替代你必须使用 {{jsxref("Object.keys")}} 或 {{jsxref("Object.entries")}} 来迭代对象的属性或属性值。
```js example-good
-var obj = { 'France': 'Paris', 'England': 'London' };
+var obj = { France: "Paris", England: "London" };
// 迭代属性名称:
for (let country of Object.keys(obj)) {
- var capital = obj[country];
- console.log(country, capital);
+ var capital = obj[country];
+ console.log(country, capital);
}
for (const [country, capital] of Object.entries(obj))
- console.log(country, capital);
+ console.log(country, capital);
```
这次 case 的另外一个选择是使用 {{jsxref("Map")}}:
```js example-good
-var map = new Map;
-map.set('France', 'Paris');
-map.set('England', 'London');
+var map = new Map();
+map.set("France", "Paris");
+map.set("England", "London");
// Iterate over the property names:
for (let country of map.keys()) {
- let capital = map[country];
- console.log(country, capital);
+ let capital = map[country];
+ console.log(country, capital);
}
-for (let capital of map.values())
- console.log(capital);
+for (let capital of map.values()) console.log(capital);
-for (const [country, capital] of map.entries())
- console.log(country, capital);
+for (const [country, capital] of map.entries()) console.log(country, capital);
```
### Iterating over a generator
@@ -77,19 +76,18 @@ function* generate(a, b) {
}
for (let x of generate) // TypeError: generate is not iterable
- console.log(x);
+ console.log(x);
```
当它没有被调用,这个 {{jsxref("Function")}} 相应的是可调用的,但是不可迭代。调用 generator 生成一个可迭代对象,该对象将迭代在生成器执行期间生成的值。
```js example-good
function* generate(a, b) {
- yield a;
- yield b;
+ yield a;
+ yield b;
}
-for (let x of generate(1,2))
- console.log(x);
+for (let x of generate(1, 2)) console.log(x);
```
### Iterating over a custom iterable
@@ -98,12 +96,12 @@ for (let x of generate(1,2))
```js example-bad
const myEmptyIterable = {
- [Symbol.iterator]() {
- return [] // [] is iterable, but it is not an iterator -- it has no next method.
- }
-}
+ [Symbol.iterator]() {
+ return []; // [] is iterable, but it is not an iterator -- it has no next method.
+ },
+};
-Array.from(myEmptyIterable); // TypeError: myEmptyIterable is not iterable
+Array.from(myEmptyIterable); // TypeError: myEmptyIterable is not iterable
```
```plain
@@ -114,12 +112,12 @@ Array.from(myEmptyIterable); // TypeError: myEmptyIterable is not iterable
```js example-good
const myEmptyIterable = {
- [Symbol.iterator]() {
- return [][Symbol.iterator]()
- }
-}
+ [Symbol.iterator]() {
+ return [][Symbol.iterator]();
+ },
+};
-Array.from(myEmptyIterable); // []
+Array.from(myEmptyIterable); // []
```
## 参阅
diff --git a/files/zh-cn/web/javascript/reference/errors/json_bad_parse/index.md b/files/zh-cn/web/javascript/reference/errors/json_bad_parse/index.md
index 0267578f609b28..1f3b06343f4e8a 100644
--- a/files/zh-cn/web/javascript/reference/errors/json_bad_parse/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/json_bad_parse/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: JSON.parse: bad parsing'
+title: "SyntaxError: JSON.parse: bad parsing"
slug: Web/JavaScript/Reference/Errors/JSON_bad_parse
---
@@ -56,7 +56,7 @@ SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
下面两行代码都会抛出错误:
```js example-bad
-JSON.parse('[1, 2, 3, 4, ]');
+JSON.parse("[1, 2, 3, 4, ]");
JSON.parse('{"foo" : 1, }');
// SyntaxError JSON.parse: unexpected character
// at line 1 column 14 of the JSON data
@@ -65,7 +65,7 @@ JSON.parse('{"foo" : 1, }');
省略末尾多余的逗号解析 JSON 就是正确:
```js example-good
-JSON.parse('[1, 2, 3, 4 ]');
+JSON.parse("[1, 2, 3, 4 ]");
JSON.parse('{"foo" : 1 }');
```
diff --git a/files/zh-cn/web/javascript/reference/errors/malformed_uri/index.md b/files/zh-cn/web/javascript/reference/errors/malformed_uri/index.md
index 7b4fc8e771dde0..56e67b1f06624d 100644
--- a/files/zh-cn/web/javascript/reference/errors/malformed_uri/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/malformed_uri/index.md
@@ -1,5 +1,5 @@
---
-title: 'URIError: malformed URI sequence'
+title: "URIError: malformed URI sequence"
slug: Web/JavaScript/Reference/Errors/Malformed_URI
---
@@ -27,17 +27,17 @@ URI 编码和解码不成功。传递给 {{jsxref("decodeURI")}}、{{jsxref("enc
编码操作会将每一个字符实例替换为一到四个相对应的 UTF-8 编码形式的转义序列。如果试图编码一个非高 - 低位完整的代理字符,将会抛出一个 {{jsxref("URIError")}} 错误,例如:
```js example-bad
-encodeURI('\uD800');
+encodeURI("\uD800");
// "URIError: malformed URI sequence"
-encodeURI('\uDFFF');
+encodeURI("\uDFFF");
// "URIError: malformed URI sequence"
```
高 - 低位完整的代理字符是没问题的,例如:
```js example-good
-encodeURI('\uD800\uDFFF');
+encodeURI("\uD800\uDFFF");
// "%F0%90%8F%BF"
```
@@ -46,14 +46,14 @@ encodeURI('\uD800\uDFFF');
解码操作则是将已经经过编码的 URL 片段中的每一个转义序列替换为相对应的字符。如果相应的字符不存在,就会抛出错误:
```js example-bad
-decodeURIComponent('%E0%A4%A');
+decodeURIComponent("%E0%A4%A");
// "URIError: malformed URI sequence"
```
输入没问题的话,通常是下面这样:
```js example-good
-decodeURIComponent('JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B');
+decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript_шеллы"
```
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_bracket_after_list/index.md b/files/zh-cn/web/javascript/reference/errors/missing_bracket_after_list/index.md
index 83a0952dc7e2de..3ffb71e5f32532 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_bracket_after_list/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_bracket_after_list/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing ] after element list'
+title: "SyntaxError: missing ] after element list"
slug: Web/JavaScript/Reference/Errors/Missing_bracket_after_list
---
@@ -40,13 +40,9 @@ var data = [{foo: "bar"} {bar: "foo"}];
```js example-good
var list = [1, 2];
-var instruments = [
- "Ukulele",
- "Guitar",
- "Piano"
-];
+var instruments = ["Ukulele", "Guitar", "Piano"];
-var data = [{foo: "bar"}, {bar: "foo"}];
+var data = [{ foo: "bar" }, { bar: "foo" }];
```
## 相关
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_colon_after_property_id/index.md b/files/zh-cn/web/javascript/reference/errors/missing_colon_after_property_id/index.md
index 6d0c28a2327a82..7acb032dc24401 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_colon_after_property_id/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_colon_after_property_id/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing : after property id'
+title: "SyntaxError: missing : after property id"
slug: Web/JavaScript/Reference/Errors/Missing_colon_after_property_id
---
@@ -20,7 +20,7 @@ SyntaxError: missing : after property id
当使用[对象初始化](/zh-CN/docs/Web/JavaScript/Reference/Operators/Object_initializer)语法创建对象的时候,需要使用半角冒号 (:) 将属性键与属性值隔开。
```js
-var obj = { propertyKey: 'value' };
+var obj = { propertyKey: "value" };
```
## 示例
@@ -37,12 +37,12 @@ var obj = { propertyKey = 'value' };
修复方法就是使用冒号,或者是在对象创建之后使用方括号语法来为其设定新的属性。
```js example-good
-var obj = { propertyKey: 'value' };
+var obj = { propertyKey: "value" };
// or alternatively
-var obj = { };
-obj['propertyKey'] = 'value';
+var obj = {};
+obj["propertyKey"] = "value";
```
### 空属性
@@ -72,7 +72,7 @@ var obj = { 'b'+'ar': 'foo' };
把计算表达式放置到方括号(`[]`)中:
```js example-good
-var obj = { ['b'+'ar']: 'foo' };
+var obj = { ["b" + "ar"]: "foo" };
```
## 相关内容
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_curly_after_function_body/index.md b/files/zh-cn/web/javascript/reference/errors/missing_curly_after_function_body/index.md
index e8850940b862fa..5de1514e33c956 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_curly_after_function_body/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_curly_after_function_body/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing } after function body'
+title: "SyntaxError: missing } after function body"
slug: Web/JavaScript/Reference/Errors/Missing_curly_after_function_body
---
@@ -37,7 +37,7 @@ var charge = function() {
正确的应该是这样的:
```js example-good
-var charge = function() {
+var charge = function () {
if (sunny) {
useSolarCells();
} else {
@@ -55,7 +55,7 @@ var charge = function() {
通常将代码语句按照层级缩进以及对缩进进行复核会有助于错误的发现。
```js example-good
-(function() {
+(function () {
if (true) {
return false;
}
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_curly_after_property_list/index.md b/files/zh-cn/web/javascript/reference/errors/missing_curly_after_property_list/index.md
index d7b1479269d0f6..f289fb22760a45 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_curly_after_property_list/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_curly_after_property_list/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing } after property list'
+title: "SyntaxError: missing } after property list"
slug: Web/JavaScript/Reference/Errors/Missing_curly_after_property_list
---
@@ -39,7 +39,7 @@ var obj = {
var obj = {
a: 1,
b: { myProp: 2 },
- c: 3
+ c: 3,
};
```
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_formal_parameter/index.md b/files/zh-cn/web/javascript/reference/errors/missing_formal_parameter/index.md
index 4fe465d557197b..fdf7ed3bfddd78 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_formal_parameter/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_formal_parameter/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing formal parameter'
+title: "SyntaxError: missing formal parameter"
slug: Web/JavaScript/Reference/Errors/Missing_formal_parameter
---
@@ -47,15 +47,15 @@ function log({ obj: "value"}) {
```js example-good
function square(number) {
return number * number;
-};
+}
function greet(greeting) {
return greeting;
-};
+}
function log(arg) {
- console.log(arg)
-};
+ console.log(arg);
+}
```
之后可以传入你想要传入的实际参数调用函数:
@@ -65,7 +65,7 @@ square(2); // 4
greet("Howdy"); // "Howdy"
-log({obj: "value"}); // Object { obj: "value" }
+log({ obj: "value" }); // Object { obj: "value" }
```
## 参见
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_initializer_in_const/index.md b/files/zh-cn/web/javascript/reference/errors/missing_initializer_in_const/index.md
index 9f67313537fb3e..0deb46183d963c 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_initializer_in_const/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_initializer_in_const/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing = in const declaration'
+title: "SyntaxError: missing = in const declaration"
slug: Web/JavaScript/Reference/Errors/Missing_initializer_in_const
---
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_name_after_dot_operator/index.md b/files/zh-cn/web/javascript/reference/errors/missing_name_after_dot_operator/index.md
index 013ccd086bfb7f..4d2ef63881d83b 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_name_after_dot_operator/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_name_after_dot_operator/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing name after . operator'
+title: "SyntaxError: missing name after . operator"
slug: Web/JavaScript/Reference/Errors/Missing_name_after_dot_operator
---
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.md b/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.md
index caf3cbddf1ce4a..28de8b6a9f8c24 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_argument_list/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing ) after argument list'
+title: "SyntaxError: missing ) after argument list"
slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_argument_list
---
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_condition/index.md b/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_condition/index.md
index 3bc39438062723..11ff9a777a24ff 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_condition/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_parenthesis_after_condition/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing ) after condition'
+title: "SyntaxError: missing ) after condition"
slug: Web/JavaScript/Reference/Errors/Missing_parenthesis_after_condition
---
@@ -59,7 +59,7 @@ if (done is true) {
```js example-good
if (done === true) {
- console.log("we are done!");
+ console.log("we are done!");
}
```
diff --git a/files/zh-cn/web/javascript/reference/errors/missing_semicolon_before_statement/index.md b/files/zh-cn/web/javascript/reference/errors/missing_semicolon_before_statement/index.md
index f07121d12c9356..1b93d2eb9b3e17 100644
--- a/files/zh-cn/web/javascript/reference/errors/missing_semicolon_before_statement/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/missing_semicolon_before_statement/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing ; before statement'
+title: "SyntaxError: missing ; before statement"
slug: Web/JavaScript/Reference/Errors/Missing_semicolon_before_statement
---
@@ -36,7 +36,7 @@ var foo = 'Tom's bar';
你可以用双引号,或者用\转义:
-```js example-good
+```js-nolint example-good
var foo = "Tom's bar";
var foo = 'Tom\'s bar';
```
@@ -76,9 +76,9 @@ def print(info){
因此,建议使用`function`而不是`def`:
```js example-good
-function print(info){
+function print(info) {
console.log(info);
-};
+}
```
## 参考
diff --git a/files/zh-cn/web/javascript/reference/errors/more_arguments_needed/index.md b/files/zh-cn/web/javascript/reference/errors/more_arguments_needed/index.md
index f8f4d1fd4a1997..43779ffb56c2d7 100644
--- a/files/zh-cn/web/javascript/reference/errors/more_arguments_needed/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/more_arguments_needed/index.md
@@ -1,5 +1,5 @@
---
-title: 'TypeError: More arguments needed'
+title: "TypeError: More arguments needed"
slug: Web/JavaScript/Reference/Errors/More_arguments_needed
---
diff --git a/files/zh-cn/web/javascript/reference/errors/negative_repetition_count/index.md b/files/zh-cn/web/javascript/reference/errors/negative_repetition_count/index.md
index feb337b1524d36..8b980c319ebcd2 100644
--- a/files/zh-cn/web/javascript/reference/errors/negative_repetition_count/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/negative_repetition_count/index.md
@@ -1,5 +1,5 @@
---
-title: 'RangeError: repeat count must be non-negative'
+title: "RangeError: repeat count must be non-negative"
slug: Web/JavaScript/Reference/Errors/Negative_repetition_count
---
@@ -25,16 +25,16 @@ RangeError: Invalid count value (Chrome)
### 无效的
```js example-bad
-'abc'.repeat(-1); // RangeError
+"abc".repeat(-1); // 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/no_non-null_object/index.md b/files/zh-cn/web/javascript/reference/errors/no_non-null_object/index.md
index b1798ec391c195..2319c26b769e4b 100644
--- a/files/zh-cn/web/javascript/reference/errors/no_non-null_object/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/no_non-null_object/index.md
@@ -28,17 +28,17 @@ TypeError: Invalid value used in weak set (Chrome)
当使用诸如 {{jsxref("Object.create()")}} 或 {{jsxref("Object.defineProperty()")}} 及{jsxref("Object.defineProperties()")}} 方法时,可选的属性描述器参数需要提供一个描述器对象。提供非对象类型的值(例如数字)将会报错:
```js example-bad
-Object.defineProperty({}, 'key', 1);
+Object.defineProperty({}, "key", 1);
// TypeError: 1 is not a non-null object
-Object.defineProperty({}, 'key', null);
+Object.defineProperty({}, "key", null);
// TypeError: null is not a non-null object
```
一个合法的描述器对象类似于下面这样:
```js example-good
-Object.defineProperty({}, 'key', { value: 'foo', writable: false });
+Object.defineProperty({}, "key", { value: "foo", writable: false });
```
### `WeakMap` 和 `WeakSet` 对象需要对象类型的键
@@ -47,14 +47,14 @@ Object.defineProperty({}, 'key', { value: 'foo', writable: false });
```js example-bad
var ws = new WeakSet();
-ws.add('foo');
+ws.add("foo");
// TypeError: "foo" is not a non-null object
```
用对象类型的值来替换:
```js example-good
-ws.add({foo: 'bar'});
+ws.add({ foo: "bar" });
ws.add(window);
```
diff --git a/files/zh-cn/web/javascript/reference/errors/no_variable_name/index.md b/files/zh-cn/web/javascript/reference/errors/no_variable_name/index.md
index d68a3f15e58db1..d8fd74d7e9cfd0 100644
--- a/files/zh-cn/web/javascript/reference/errors/no_variable_name/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/no_variable_name/index.md
@@ -1,5 +1,5 @@
---
-title: 'SyntaxError: missing variable name'
+title: "SyntaxError: missing variable name"
slug: Web/JavaScript/Reference/Errors/No_variable_name
---
@@ -60,11 +60,12 @@ var second = document.getElementById('two'),
修复后的代码:
```js example-good
-var x, y = "foo";
+var x,
+ y = "foo";
var x = "foo";
-var first = document.getElementById('one');
-var second = document.getElementById('two');
+var first = document.getElementById("one");
+var second = document.getElementById("two");
```
### 数组
@@ -79,7 +80,7 @@ var arr = 1,2,3,4,5;
这样写才是正确的:
```js example-good
-var arr = [1,2,3,4,5];
+var arr = [1, 2, 3, 4, 5];
```
## 相关内容
diff --git a/files/zh-cn/web/javascript/reference/errors/non_configurable_array_element/index.md b/files/zh-cn/web/javascript/reference/errors/non_configurable_array_element/index.md
index 3b60d565b1c83f..11e42a42de6667 100644
--- a/files/zh-cn/web/javascript/reference/errors/non_configurable_array_element/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/non_configurable_array_element/index.md
@@ -1,5 +1,5 @@
---
-title: 'TypeError: can''t delete non-configurable array element'
+title: "TypeError: can't delete non-configurable array element"
slug: Web/JavaScript/Reference/Errors/Non_configurable_array_element
---
@@ -32,8 +32,8 @@ TypeError: Cannot delete property '2' of [object Array] (Chrome)
```js example-bad
var arr = [];
-Object.defineProperty(arr, 0, {value: 0});
-Object.defineProperty(arr, 1, {value: "1"});
+Object.defineProperty(arr, 0, { value: 0 });
+Object.defineProperty(arr, 1, { value: "1" });
arr.length = 1;
// TypeError: can't delete non-configurable array element
@@ -43,8 +43,8 @@ arr.length = 1;
```js example-good
var arr = [];
-Object.defineProperty(arr, 0, {value: 0, configurable: true});
-Object.defineProperty(arr, 1, {value: "1", configurable: true});
+Object.defineProperty(arr, 0, { value: 0, configurable: true });
+Object.defineProperty(arr, 1, { value: "1", configurable: true });
arr.length = 1;
```
@@ -54,7 +54,7 @@ arr.length = 1;
{{jsxref("Object.seal()")}} 函数会将数组中现存的所有元素标记为不可配置。
```js example-bad
-var arr = [1,2,3];
+var arr = [1, 2, 3];
Object.seal(arr);
arr.length = 1;
@@ -64,7 +64,7 @@ arr.length = 1;
(为了解决上述问题,)或者是移除 {{jsxref("Object.seal()")}} 调用,或者将数组拷贝一份。在拷贝数组的情况下,缩短备份数组的长度并不会修改原始数组的长度。
```js example-good
-var arr = [1,2,3];
+var arr = [1, 2, 3];
Object.seal(arr);
// Copy the initial array to shorten the copy
diff --git a/files/zh-cn/web/javascript/reference/errors/not_a_constructor/index.md b/files/zh-cn/web/javascript/reference/errors/not_a_constructor/index.md
index 741c719d32d11a..7527e9f595db52 100644
--- a/files/zh-cn/web/javascript/reference/errors/not_a_constructor/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/not_a_constructor/index.md
@@ -46,8 +46,8 @@ new Math();
new Symbol();
// TypeError: Symbol is not a constructor
-function* f() {};
-var obj = new f;
+function* f() {}
+var obj = new f();
// TypeError: f is not a constructor
```
@@ -83,7 +83,9 @@ return new Promise.resolve(true);
```js
// 这是合法的,但是没必要这么长:
-return new Promise((resolve, reject) => { resolve(true); })
+return new Promise((resolve, reject) => {
+ resolve(true);
+});
// 用静态方法来代替:
return Promise.resolve(true);
diff --git a/files/zh-cn/web/javascript/reference/errors/not_a_function/index.md b/files/zh-cn/web/javascript/reference/errors/not_a_function/index.md
index e1e949ebc84a0a..d5845cb2244b29 100644
--- a/files/zh-cn/web/javascript/reference/errors/not_a_function/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/not_a_function/index.md
@@ -56,7 +56,7 @@ var x = document.getElementById("foo");
```js example-bad
var obj = { a: 13, b: 37, c: 42 };
-obj.map(function(num) {
+obj.map(function (num) {
return num * 2;
});
@@ -68,7 +68,7 @@ obj.map(function(num) {
```js example-good
var numbers = [1, 4, 9];
-numbers.map(function(num) {
+numbers.map(function (num) {
return num * 2;
});
@@ -81,17 +81,16 @@ numbers.map(function(num) {
```js example-bad
var Dog = function () {
- this.age = 11;
- this.color = "black";
- this.name = "Ralph";
- return this;
-}
-
-Dog.prototype.name = function(name) {
- this.name = name;
- return this;
-}
+ this.age = 11;
+ this.color = "black";
+ this.name = "Ralph";
+ return this;
+};
+Dog.prototype.name = function (name) {
+ this.name = name;
+ return this;
+};
var myNewDog = new Dog();
myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function
@@ -101,17 +100,16 @@ myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function
```js example-good
var Dog = function () {
- this.age = 11;
- this.color = "black";
- this.dogName = "Ralph"; //Using this.dogName instead of .name
- return this;
-}
-
-Dog.prototype.name = function(name) {
- this.dogName = name;
- return this;
-}
+ this.age = 11;
+ this.color = "black";
+ this.dogName = "Ralph"; //Using this.dogName instead of .name
+ return this;
+};
+Dog.prototype.name = function (name) {
+ this.dogName = name;
+ return this;
+};
var myNewDog = new Dog();
myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }
@@ -125,7 +123,7 @@ myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }
```js example-bad
const sixteen = 2(3 + 5);
-alert('2 x (3 + 5) is ' + String(sixteen));
+alert("2 x (3 + 5) is " + String(sixteen));
//Uncaught TypeError: 2 is not a function
```
@@ -133,7 +131,7 @@ alert('2 x (3 + 5) is ' + String(sixteen));
```js example-good
const sixteen = 2 * (3 + 5);
-alert('2 x (3 + 5) is ' + String(sixteen));
+alert("2 x (3 + 5) is " + String(sixteen));
//2 x (3 + 5) is 16
```
diff --git a/files/zh-cn/web/javascript/reference/errors/not_defined/index.md b/files/zh-cn/web/javascript/reference/errors/not_defined/index.md
index 1f5fcac19e5df6..df41c0fbaa6a95 100644
--- a/files/zh-cn/web/javascript/reference/errors/not_defined/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/not_defined/index.md
@@ -32,7 +32,7 @@ foo.substring(1); // ReferenceError: foo is not defined
“foo”变量没有在任何地方被声明。它需要是某种字符串,这样 {{jsxref("String.prototype.substring()")}} 方法才可以正常工作。
```js example-good
-var foo = 'bar';
+var foo = "bar";
foo.substring(1); // "ar"
```
@@ -41,9 +41,9 @@ foo.substring(1); // "ar"
变量必须是在它当前的执行环境中可用的。在一个函数([function](/zh-CN/docs/Web/JavaScript/Reference/Functions))中定义的变量不能从这个函数外部的任何地方访问,因为这个变量的作用域仅在这个函数的内部。
```js example-bad
-function numbers () {
+function numbers() {
var num1 = 2,
- num2 = 3;
+ num2 = 3;
return num1 + num2;
}
@@ -54,9 +54,9 @@ console.log(num1); // ReferenceError num1 is not defined.
```js example-good
var num1 = 2,
- num2 = 3;
+ num2 = 3;
-function numbers () {
+function numbers() {
return num1 + num2;
}
diff --git a/files/zh-cn/web/javascript/reference/errors/precision_range/index.md b/files/zh-cn/web/javascript/reference/errors/precision_range/index.md
index 13a4d63385036d..99373feebf9aa0 100644
--- a/files/zh-cn/web/javascript/reference/errors/precision_range/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/precision_range/index.md
@@ -1,5 +1,5 @@
---
-title: 'RangeError: precision is out of range'
+title: "RangeError: precision is out of range"
slug: Web/JavaScript/Reference/Errors/Precision_range
---
@@ -28,39 +28,39 @@ RangeError: toPrecision() argument must be between 1 and 21 (Chrome)
通常这些方法允许的参数范围介于 0 和 20(或 21)之间。需要注意的是,ECMAScript 标准是允许扩展这个范围的。
-| Method | Firefox (SpiderMonkey) | Chrome, Opera (V8) |
-| ------------------------------------------------------------ | ---------------------- | ------------------ |
+| Method | Firefox (SpiderMonkey) | Chrome, Opera (V8) |
+| ---------------------------------------------- | ---------------------- | ------------------ |
| {{jsxref("Number.prototype.toExponential()")}} | 0 to 100 | 0 to 20 |
-| {{jsxref("Number.prototype.toFixed()")}} | -20 to 100 | 0 to 20 |
-| {{jsxref("Number.prototype.toPrecision()")}} | 1 to 100 | 1 to 21 |
+| {{jsxref("Number.prototype.toFixed()")}} | -20 to 100 | 0 to 20 |
+| {{jsxref("Number.prototype.toPrecision()")}} | 1 to 100 | 1 to 21 |
## 示例
### 错误的示例
```js example-bad
-77.1234.toExponential(-1); // RangeError
-77.1234.toExponential(101); // RangeError
+(77.1234).toExponential(-1); // RangeError
+(77.1234).toExponential(101); // RangeError
-2.34.toFixed(-100); // RangeError
-2.34.toFixed(1001); // RangeError
+(2.34).toFixed(-100); // RangeError
+(2.34).toFixed(1001); // RangeError
-1234.5.toPrecision(-1); // RangeError
-1234.5.toPrecision(101); // RangeError
+(1234.5).toPrecision(-1); // RangeError
+(1234.5).toPrecision(101); // RangeError
```
### 正确的示例
```js example-good
-77.1234.toExponential(4); // 7.7123e+1
-77.1234.toExponential(2); // 7.71e+1
+(77.1234).toExponential(4); // 7.7123e+1
+(77.1234).toExponential(2); // 7.71e+1
-2.34.toFixed(1); // 2.3
-2.35.toFixed(1); // 2.4 (note that it rounds up in this case)
+(2.34).toFixed(1); // 2.3
+(2.35).toFixed(1); // 2.4 (note that it rounds up in this case)
-5.123456.toPrecision(5); // 5.1235
-5.123456.toPrecision(2); // 5.1
-5.123456.toPrecision(1); // 5
+(5.123456).toPrecision(5); // 5.1235
+(5.123456).toPrecision(2); // 5.1
+(5.123456).toPrecision(1); // 5
```
## 相关页面
diff --git a/files/zh-cn/web/javascript/reference/errors/property_access_denied/index.md b/files/zh-cn/web/javascript/reference/errors/property_access_denied/index.md
index e02bc94596df85..6f7753ebc7f603 100644
--- a/files/zh-cn/web/javascript/reference/errors/property_access_denied/index.md
+++ b/files/zh-cn/web/javascript/reference/errors/property_access_denied/index.md
@@ -22,12 +22,14 @@ Error: Permission denied to access property "x"
## 示例
```html
-
+
-
+
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
当 x ≥ 1 x \geq 1 时,都有 arcosh ( x ) = ln ( x + x 2 - 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 + x 2 + 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);
我们可以尝试在文档中嵌入 [`