fix(guide): simplify directory structure

This commit is contained in:
Mrugesh Mohapatra
2018-10-16 21:26:13 +05:30
parent f989c28c52
commit da0df12ab7
35752 changed files with 0 additions and 317652 deletions

View File

@@ -0,0 +1,129 @@
---
title: JavaScript Tutorials and Other Resources
localeTitle: JavaScript教程和其他资源
---
* [适用于猫的JavaScript](http://jsforcats.com/)
* [现代JavaScript教程](https://javascript.info/)
* [弗里斯比教授的功能编程指南](https://github.com/DrBoolean/mostly-adequate-guide)
* [雄辩的Javascript](http://www.eloquentjavascript.net) [_注释_](https://watchandcode.com/courses/eloquent-javascript-the-annotated-version)
* [说到Javascript](http://speakingjs.com/es5/)
* [探索ES6](http://exploringjs.com/es6/)
* [Udemy - Javascript了解奇怪的部分 _前3.5小时_ ](https://www.youtube.com/watch?v=Bv_5Zv5c-Ts)
* [JavaScript中的函数编程](https://www.youtube.com/playlist?list=PL0zVEGEvSaeEd9hlmCXrk5yUyqUag-n84)
* [JavaScript简介第一步](https://www.educative.io/collection/5679346740101120/5720605454237696?authorName=Arnav%20Aggarwal)
* [Douglas Crockford的视频](https://www.youtube.com/watch?v=v2ifWcnQs6M&index=1&list=PL62E185BB8577B63D)
* [现代JS Cheatsheet](https://mbeaudru.github.io/modern-js-cheatsheet/)
* [学习JavaScript的50个最佳网站](http://www.codeconquest.com/blog/top-50-websites-to-learn-javascript/)
* [Codementor JavaScript教程](https://www.codementor.io/community/topic/javascript)
* [你可能不需要jQuery](http://youmightnotneedjquery.com/)
## 参考
* [DevDocs](http://devdocs.io)
* [OverAPI JavaScript备忘单](http://overapi.com/javascript)
* [ECMA-262](http://www.ecma-international.org/publications/standards/Ecma-262.htm)
* [Mozilla开发者网络MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript)
在[http://jster.net上](http://jster.net)找到javascript库
## 快速JavaScript
* [REPL](https://repl.it/languages/Javascript) [_节点_](https://repl.it/languages/iojs/)
* [JSBin](http://jsbin.com)
* [的jsfiddle](https://jsfiddle.net)
* [CodePen](http://codepen.io)
* [CoderPad结_对编程_ ](http://coderpad.io)
* [C9 _IDE_ 结_对编程_ ](http://c9.io)
* [对象游乐场( _可视化对象_ ](http://www.objectplayground.com/)
* [Plunker](http://plnkr.co)
## 挑战
* [代码大战](http://codewars.com)
* [黑客等级](https://hackerrank.com)
* [编码游戏](http://codingame.com)
* [CodeFights](https://codefights.com/home)
* [ES6 Katas](http://es6katas.org)
## 教程
* [Codecademy网站](https://www.codecademy.com)
* [RithmSchool](https://www.rithmschool.com)
## 演习
* [Codility](https://codility.com/programmers/lessons/)
* [Coderbyte](http://coderbyte.com)
* [Exercism](http://exercism.io)
* [JavaScript30](https://javascript30.com/)
* [Javascript.comPluralsight](https://www.javascript.com/)
## 编者
* [Visual Studio代码](https://code.visualstudio.com/)
Visual Studio Code包含对IntelliSense代码完成的内置支持丰富的语义代码理解和导航以及代码重构。它带有内置的调试器和git支持并具有大量扩展。
* [Webstorm](https://www.jetbrains.com/webstorm/)
适用于Javascript的全功能IDE包括代码完成以及对实时linting版本控制和测试的支持。由Jet Brains制作并以IntelliJ Java IDE为模型。
* [括号](http://brackets.io)
* [原子](http://atom.io)
由GitHub制作的开源文本编辑器。
* [崇高文本](https://www.sublimetext.com/)
## 博客
* [完美杀戮](http://perfectionkills.com)
* [2ality](http://www.2ality.com/)
* [媒体上的JS集合](https://medium.com/the-javascript-collection)
* [大卫沃尔什](https://davidwalsh.name/)
* [superheroJS](http://superherojs.com/)
## 播客
* [JS Jabber](https://devchat.tv/js-jabber)
## 视频教程
* [Derek Banas在一个视频中学习JS](https://www.youtube.com/watch?v=fju9ii8YsGs)
* [Derek Banas的面向对象的JavaScript](https://www.youtube.com/watch?v=O8wwnhdkPE4)
## 图书
* [JavaScript忍者的秘密](https://www.manning.com/books/secrets-of-the-javascript-ninja)
* [JavaScript应用程序编程](http://pjabook.com/)
* [可维护的JavaScript](http://shop.oreilly.com/product/0636920025245.do)
* [学习JavaScript设计模式](http://addyosmani.com/resources/essentialjsdesignpatterns/book/)
* [Airbnb JavaScript风格指南](https://github.com/airbnb/javascript)
* [JSDoc](http://usejsdoc.org/)
* [Javascript Allonge Six](https://leanpub.com/javascriptallongesix/read)
* [你不懂JS](https://github.com/getify/You-Dont-Know-JS)
由Kyle Simpson撰写的6本关于JavaScript的书籍。从初学者到高级。
* [雄辩的Javascript](http://www.eloquentjavascript.net)
精彩全面地介绍Javascript的基础知识和功能并配有浏览器内交互式代码
* [弗里斯比教授的功能编程指南](https://github.com/DrBoolean/mostly-adequate-guide)
在Javascript中进行功能编程的相当深入的指南
* [JavaScript方式](https://github.com/bpesquet/thejsway)
* [功能性灯JS](https://github.com/getify/Functional-Light-JS)
本书旨在成为任何希望重新发现JavaScript的许多方面的人的有用伴侣。从编程的基础知识到前端和后端Web开发许多主题都以简单易懂的方式介绍。无需先验知识

View File

@@ -0,0 +1,24 @@
---
title: Advantages and Disadvantages of JavaScript
localeTitle: JavaScript的优点和缺点
---
# JavaScript的优点和缺点
与所有计算机语言一样JavaScript具有某些优点和缺点。许多优点和缺点都与JavaScript经常在客户端浏览器中执行有关但现在还有其他方法可以使用JavaScript使其具有与服务器端语言相同的优点。
## JavaScript的优点
* **速度** 。客户端JavaScript非常快因为它可以在客户端浏览器中立即运行。除非需要外部资源否则JavaScript不会受到后端服务器的网络调用的阻碍。它也没有必要在客户端编译这给了它一定的速度优势授予增加一些风险取决于所开发代码的质量
* **简单** 。 JavaScript的学习和实现相对简单。
* **人气** 。 JavaScript在Web中随处可用。学习JavaScript的资源很多。 StackOverflow和GitHub有许多使用Javascript的项目并且语言作为一个整体近年来在业界获得了很大的关注尤其是。
* **互操作性** 。 JavaScript可以很好地与其他语言一起使用并且可以在各种各样的应用程序中使用。与PHP或[SSI](https://en.wikipedia.org/wiki/Server_Side_Includes)脚本不同JavaScript可以插入任何网页无论文件扩展名如何。 JavaScript也可以在用其他语言编写的脚本中使用例如Perl和PHP。
* **服务器负载** 。客户端减少了对网站服务器的需求。
* **丰富的接口** 。拖放组件或滑块可以为您的网站提供丰富的界面。
* **扩展功能** 。像Greasemonkey这样的第三方附加组件使JavaScript开发人员能够编写可以在所需网页上执行以扩展其功能的JavaScript代码片段。
* **多功能性** 。如今有许多方法可以通过Node.js服务器使用JavaScript。如果您使用Express引导node.js使用像mongodb这样的文档数据库并在前端为客户端使用JavaScript则可以仅使用JavaScript从前到后开发整个JavaScript应用程序。
* **更新** 。自从EcmaScript 5Javascript依赖的脚本规范出现以来Ecma International一直致力于每年更新JavaScript。到目前为止我们已经在2017年获得了ES6的浏览器支持并期待在未来几个月内支持ES7。
## JavaScript的缺点
* **客户端安全性** 。因为代码在用户的计算机上执行所以在某些情况下它可能被用于恶意目的。这是一些人选择禁用Javascript的原因之一。
* **浏览器支持** 。 JavaScript有时会被不同的浏览器区别对待。虽然服务器端脚本总是会产生相同的输出但客户端脚本可能有点不可预测。不要过分关注这一点 - 只要你在所有主流浏览器中测试你的脚本就应该是安全的。此外,还有一些服务允许您在检查更新时自动测试代码,以确保所有浏览器都支持您的代码。

View File

@@ -0,0 +1,65 @@
---
title: Angularjs Interview Questions
localeTitle: Angularjs访谈问题
---
# Angularjs访谈问题
以下是Angularjs访谈中经常被问到的概念列表。
* 什么是AngularJS
* 什么是模型视图控制器MVC
* 双向数据绑定
* 什么是依赖注入?它是如何工作的?
* AngularJS中的$ scope是什么
* 什么是AngularJS中的$ rootScope
* 如何在Angular中实现路由
* 解释指令
* 我们如何在Angular中创建自定义指令
* 解释服务和工厂之间的差异
* 解释$ q服务延期和承诺
# 示例问题和解答
问题列出AngularJS中的指令 答案ngBindngModelngClassngAppngInitngRepeat
问题AngularJS中的$ scope是什么 答案AngularJS中的$ scope是一个引用应用程序模型的对象。它是一个将视图DOM元素与控制器绑定的对象。在控制器中模型数据通过$ scope对象访问。众所周知AngularJS支持MV \*模式,$ scope对象成为MV \*的模型。
问题AngularJS中的SPA单页面应用程序是什么 答案单页面应用程序SPA是一种Web应用程序它可以加载单个HTML页面并在用户与应用程序交互时动态更新该页面。 SPA使用AJAX和HTML来创建流畅且响应迅速的Web应用程序而无需不断的页面重新加载。但是这意味着大部分工作都发生在客户端在JavaScript中。 这里的单个HTML页面表示来自服务器的UI响应页面。源可以是ASPASP.NETASP.NET MVCJSP等。 但是单页Web应用程序作为一个页面提供给浏览器并且通常不需要在用户导航到应用程序的各个部分时重新加载页面。这样可以为最终用户提供更快的导航更高效的网络传输和更好的整体性能。
问题AngularJS中的路由是什么路由是AngularJS的核心功能。此功能在构建具有多个视图的SPA单页应用程序时非常有用。在SPA应用程序中所有视图都是不同的Html文件我们使用Routing来加载应用程序的不同部分这有助于逻辑划分应用程序并使其可管理。换句话说Routing帮助我们在逻辑视图中划分应用程序并将它们与不同的控制器绑定。
问题:解释重复指令。 答案ng-repeat指令是最常用且非常有用的AngularJS指令功能。它迭代一组项目并创建DOM元素。它会不断监视数据源以便根据更改重新呈现模板。
问题ng-If和ng-show / ng-hide有什么区别。 答案如果condition为true则ng-If指令仅呈现DOM元素。其中ng-show / ng-hide指令呈现DOM元素但它更改了ng-hide / ng-show的类以保持页面上元素的可见性。
问题如何使用AngularJs取消超时 答案:$ timeout是AngularJs的window.setTimeout包装器你取消应用该函数的超时
```
$timeout.cancel(function (){
// write your code.
});
```
问题:什么是依赖注入? 答案依赖注入DI是一种软件设计模式用于处理组件如何获取其依赖关系。 AngularJS注入器子系统负责创建组件解析它们的依赖关系并根据请求将它们提供给其他组件。
问题:解释-App指令。 答案ng-app指令启动AngularJS应用程序。它定义了根元素。当加载包含AngularJS Application的网页时它会自动初始化或引导应用程序。它还用于在AngularJS Application中加载各种AngularJS模块。
问题:解释-init指令 答案ng-init指令初始化AngularJS应用程序数据。它用于将值放入要在应用程序中使用的变量。例如在下面的示例中我们使用JSON语法初始化了一组国家/地区,以定义国家/地区数组。
```html
<div ng-app = "" ng-init = "countries = [{locale:'en-US',name:'United States'}, {locale:'en-GB',name:'United Kingdom'}, {locale:'en-FR',name:'France'}]">
...
</div>
```
问题:如何在控制器之间共享数据? 答案创建一个AngularJS服务该服务将保存数据并将其注入控制器内部。 使用服务是最干净,最快速和最简单的测试方式。但是,有几种其他方法可以在控制器之间实现数据共享,例如: - 使用事件 - 使用$ parentnextSiblingcontrollerAs等直接访问控制器 - 使用$ rootScope添加数据不是一个好习惯
问题ng-if和ng-show / hide指令有什么区别 答案ng-if仅在条件为真时创建并显示DOM元素如果条件为false或更改为false则不会创建或销毁创建的元素。 ng-show / hide将始终生成DOM元素但它将根据条件的评估应用css display属性。
#### 更多信息:
在这里您可以找到其他问题和答案:
* [AngularJS面试问题](https://www.tutorialspoint.com/angularjs/angularjs_interview_questions.htm)
* [10 AngularJS面试问答](https://www.upwork.com/i/interview-questions/angularjs/)
* [50个最重要的AngularJS面试问题取得100的成功](http://www.techbeamers.com/latest-angularjs-interview-questions-answers/)

View File

@@ -0,0 +1,79 @@
---
title: Arguments
localeTitle: 参数
---
arguments对象是一个**类似于数组的对象** _因为_ **对象** _的结构类似于数组的结构但它不应该被认为是一个数组因为它具有对象的所有功能_ 它存储了你的所有参数传递给函数特别是该函数专有。如果要将3个参数传递给函数比如`storeNames()` ,那么这三个参数将存储在一个名为**arguments**的对象中,当我们传递参数`storeNames("Mulder", "Scully", "Alex Krycek")`它将看起来像这样`storeNames("Mulder", "Scully", "Alex Krycek")`我们的功能:
* 首先我们声明一个函数并使其返回arguments对象。
\`\`\`的JavaScript
function storeNames{return arguments; }
```
* Then, when we execute that function with **n arguments**, 3 in this case, it will return the object to us and it will **look like** an array. We can convert it to an array, but more on that later...
```
JavaScript的 //如果我们在控制台中执行以下行: storeNames“Mulder”“Scully”“Alex Kryceck”; //输出为{'0''Mulder''1''Scully''2''Alex Kryceck'}
```
If you want to know more about this, such as converting it to an array or the optimization problem that comes with using the _slice(_) method and how to solve it, click on **read more** (Gitter Chat Only).
## Treat it as an array
You can invoke arguments by using `arguments[n]` (where _n_ is the index of the argument in the array-like object) but if you want to use it as an array for iteration purposes or applying array methods to it, you need to _convert it to an array_ by declaring a variable and using the Array.prototype.slice.call method (because _arguments_ is not an array):
```
JavaScript的 var args = Array.prototype.slice.callarguments;
//或es6方式 var args = Array.fromarguments
```
Since **slice()** has two (the parameter **end** is optional) parameters, you can grab a certain portion of the arguments by specifying (using the _slice.call()_ method renders these two parameters optional, not just _end_) the beginning and the ending of your portion; check out the following code:
```
JavaScript的 function getGrades{ var args = Array.prototype.slice.callarguments1,3; 回归 }
//让我们输出这个! console.loggetGrades90,100,75,40,89,95;
//输出应该是:// // \[100,75\] < - 为什么因为它从索引1开始并在索引3处停止 //所以没有考虑索引340)。 // //如果我们删除'3'参数只留下参数1我们得到 //来自索引1的每个参数\[100,75,40,89,95\]
```
### Optimization issues with Array.slice()
There is a little problem, it's not recommended to use slice in the arguments object (optimization reasons)...
> **Important**: You should not slice on arguments because it prevents optimizations in JavaScript engines (V8 for example). Instead, try constructing a new array by iterating through the arguments object.
>
> _by_ **_Mozilla Developer Network_** <a href='https://developer.mozilla.org/ca/docs/Web/JavaScript/Reference/Functions/arguments' target='_blank' rel='nofollow'>(reference)<a>
So, what other method is available to convert _arguments_ to an array? I recommend the for-loop (not the for-in loop), you can do it like this:
```
JavaScript的 var args = \[\]; //首先是空数组 forvar i = 0; i <arguments.length; i ++{ args.push参数\[I\] } //现在'args'是一个包含你的参数的数组 \`\`\`
有关优化问题的更多信息
优化杀手 [管理参数](https://github.com/petkaantonov/bluebird/wiki/Optimization-killers#3-managing-arguments)
### ES6 rest参数作为绕过arguments对象的一种方式
在ES2015 / ES6中可以在大多数地方使用rest参数 `...` 而不是arguments对象假设我们有以下功能非ES6
```
function getIntoAnArgument() {
var args = arguments.slice();
args.forEach(function(arg) {
console.log(arg);
});
}
```
该功能可以在ES6中替换为
```
function getIntoAnArgument(...args) {
args.forEach(arg => console.log(arg));
}
```
请注意我们还使用了箭头函数来缩短forEach回调
参数对象在箭头函数的主体内不可用
rest参数必须始终作为函数定义中的最后一个参数
`function getIntoAnArgument(arg1, arg2, arg3, ...restOfArgs /*no more arguments allowed here*/) { //function body }`

View File

@@ -0,0 +1,128 @@
---
title: Arithmetic Operation
localeTitle: 算术运算
---
JavaScript为用户提供了五个算术运算符 `+` `-` `*` `/``%` 。运算符分别用于加法,减法,乘法,除法和余数。
## 加成
**句法**
`a + b`
**用法**
```
2 + 3 // returns 5
true + 2 // interprets true as 1 and returns 3
false + 5 // interprets false as 0 and returns 5
true + "bar" // concatenates the boolean value and returns "truebar"
5 + "foo" // concatenates the string and the number and returns "5foo"
"foo" + "bar" // concatenates the strings and returns "foobar"
```
_提示_有一个方便的[增量](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Increment_()运算符当你将数字加1时这是一个很好的快捷方式。
## 减法
**句法**
`a - b`
**用法**
```
2 - 3 // returns -1
3 - 2 // returns 1
false - 5 // interprets false as 0 and returns -5
true + 3 // interprets true as 1 and returns 4
5 + "foo" // returns NaN (Not a Number)
```
_提示_有一个方便的[减量](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Decrement_(--)运算符当你用1减去数字时这是一个很好的捷径。
## 乘法
**句法**
`a * b`
**用法**
```
2 * 3 // returns 6
3 * -2 // returns -6
false * 5 // interprets false as 0 and returns 0
true * 3 // interprets true as 1 and returns 3
5 * "foo" // returns NaN (Not a Number)
Infinity * 0 // returns NaN
Infinity * Infinity // returns Infinity
```
## 师
**句法**
`a / b`
**用法**
```
3 / 2 // returns 1.5
3.0 / 2/0 // returns 1.5
3 / 0 // returns Infinity
3.0 / 0.0 // returns Infinity
-3 / 0 // returns -Infinity
false / 5 // interprets false as 0 and returns 0
true / 2 // interprets true a 1 and returns 0.5
5 + "foo" // returns NaN (Not a Number)
Infinity / Infinity // returns NaN
```
## 剩余
**句法**
`a % b`
**用法**
```
3 % 2 // returns 1
true % 5 // interprets true as 1 and returns 1
false % 4 // interprets false as 0 and returns 0
3 % "bar" // returns NaN
```
## 增量
**句法**
`a++ or ++a`
**用法**
```
// Postfix
x = 3; // declare a variable
y = x++; // y = 4, x = 3
// Prefix
var a = 2;
b = ++a; // a = 3, b = 3
```
## 递减
**句法**
`a-- or --a`
**用法**
```
// Postfix
x = 3; // declare a variable
y = x--; // y = 3, x = 3
// Prefix
var a = 2;
b = --a; // a = 1, b = 1
```
_重要_如您所见您**无法**对`Infinity`执行任何操作。
资料来源:令人惊叹的[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators) 。

View File

@@ -0,0 +1,66 @@
---
title: Arrow Functions
localeTitle: 箭头功能
---
Arrow函数是用于编写JavaScript函数表达式的新ES6语法。较短的语法节省了时间并简化了功能范围。
## 什么是箭头功能?
箭头函数表达式是使用“胖箭头”标记( `=>` )编写函数表达式的更简洁的语法。
### 基本语法
以下是箭头功能的基本示例:
```javascript
// ES5 syntax
var multiply = function(x, y) {
return x * y;
};
// ES6 arrow function
var multiply = (x, y) => { return x * y; };
// Or even simpler
var multiply = (x, y) => x * y;
```
您不再需要`function``return`关键字,甚至是大括号。
### 简化了`this`
在箭头函数之前,新函数定义了它们自己的`this`值。要在传统的函数表达式中使用`this` ,我们必须编写一个类似的解决方法:
```javascript
// ES5 syntax
function Person() {
// we assign `this` to `self` so we can use it later
var self = this;
self.age = 0;
setInterval(function growUp() {
// `self` refers to the expected object
self.age++;
}, 1000);
}
```
箭头功能没有定义它自己的`this`值,它继承了`this`从封闭功能:
```javascript
// ES6 syntax
function Person(){
this.age = 0;
setInterval(() => {
// `this` now refers to the Person object, brilliant!
this.age++;
}, 1000);
}
var p = new Person();
```
#### 进一步阅读
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions)

View File

@@ -0,0 +1,65 @@
---
title: Assignment Operators
localeTitle: 分配运营商
---
# 分配运营商
赋值运算符,顾名思义,为变量赋值(或重新赋值)。虽然赋值运算符有很多变化,但它们都是基本赋值运算符的构建。
## 句法
`x = y;` |说明|必要性 ---------|---------------------|---------
`x` |变量|需要
`=` |分配操作员|需要
`y` |赋值给变量的值需要
## 例子
```
let initialVar = 5; // Variable initialization requires the use of an assignment operator
let newVar = 5;
newVar = 6; // Variable values can be modified using an assignment operator
```
## 变化
其他赋值运算符是使用变量由上面的x表示和值由上面的y表示执行某些操作的简写然后将结果赋给变量本身。
例如,下面是加法赋值运算符的语法:
```
x += y;
```
这与应用加法运算符并将总和重新分配给原始变量即x相同可以通过以下代码表示
```
x = x + y;
```
为了使用实际值来说明这一点,下面是使用加法赋值运算符的另一个示例:
```
let myVar = 5; // value of myVar: 5
myVar += 7; // value of myVar: 12 = 5 + 7
```
## Javascript的赋值运算符的完整列表
运营商|语法|长版
\------------------------------- | --------- | -------------
作业| x = y | x = y
添加任务| x + = y | x = x + y
减法赋值| x - = y | x = x - y
乘法赋值| x \* = y | x = x \* y
部门分配| x / = y | x = x / y
剩余任务| x= y | x = xy
指数分配| x \*\* = y | x = x \*\* y
左移分配| x << = y | x = x << y 右移分配| x >> = y | x = x >> y
无符号右移分配| x >>> = y | x = x >>> y
按位AND赋值| x= y | x = xy
按位异或分配| x ^ = y | x = x ^ y
按位OR赋值| x | = y | x = x | ÿ
### 更多信息:
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators#Assignment)
[MSDN链接](https://docs.microsoft.com/en-us/scripting/javascript/reference/assignment-operator-decrement-equal-javascript)

View File

@@ -0,0 +1,125 @@
---
title: Async messaging with RabbitMQ and Tortoise
localeTitle: 与RabbitMQ和Tortoise的异步消息传递
---
RabbitMQ恰好是目前使用AMQ协议的最简单性能最高的消息代理平台。在微服务架构中使用它可以带来巨大的性能提升以及可靠性的承诺。在本指南中我们将探讨将RabbitMQ与Node.js一起使用的基础知识。
## 理论
在最基本的层面上理想情况下您可以通过Rabbit _发布者_和_订阅者_彼此交互两种不同的服务。发布者通常将消息推送到Rabbit订阅者监听这些消息并根据这些消息执行代码。请注意它们可以同时发生 - 服务可以将消息发布到Rabbit并同时使用消息这样就可以设计出非常强大的系统。
现在发布者通常会将带有_路由密钥的_消息发布到称为_交换的_东西。使用者侦听绑定到路由键的同一交换机上的_队列_ 。在架构方面您的平台将使用一个Rabbit交换并且不同类型的作业/服务将具有自己的路由键和队列以使pub-sub有效地工作。消息可以是字符串;它们也可以是本机对象--AMQP客户端库可以将对象从一种语言转换为另一种语言。是的这确实意味着服务可以用不同的语言编写只要他们能够理解AMQP。
## 入门
我们将编写一个非常简单的示例其中发布者脚本向Rabbit发布消息其中包含URL消费者脚本侦听Rabbit获取已发布的URL调用它并显示结果。您可以在[Github](https://github.com/rudimk/freecodecamp-guides-rabbitmq-tortoise)上找到完成的样本。
首先让我们初始化一个npm项目
`$ npm init`
您始终只需`Enter`并使用默认选项 - 或者您可以填写它们。现在,让我们安装我们需要的软件包。我们将使用[Tortoise](https://www.npmjs.com/package/tortoise)与RabbitMQ进行交互。我们还将使用[node-cron](https://www.npmjs.com/package/node-cron)来安排实际的消息发布。
`$ npm install --save tortoise node-cron`
现在你的`package.json`应该看起来像这样:
```
{
"name": "freecodecamp-guides-rabbitmq-tortoise",
"version": "1.0.0",
"description": "Sample code to accompany the FreeCodeCamp guide on async messaging with RabbitMQ and Tortoise.",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rudimk/freecodecamp-guides-rabbitmq-tortoise.git"
},
"keywords": [
"rabbitmq",
"tortoise",
"amqp"
],
"author": "Rudraksh MK",
"license": "MIT",
"bugs": {
"url": "https://github.com/rudimk/freecodecamp-guides-rabbitmq-tortoise/issues"
},
"homepage": "https://github.com/rudimk/freecodecamp-guides-rabbitmq-tortoise#readme",
"dependencies": {
"node-cron": "^1.2.1",
"tortoise": "^1.0.1"
}
}
```
现在我们都准备好了。我们先创建一个发布者。
```javascript
const Tortoise = require('tortoise')
const cron = require('node-cron')
const tortoise = new Tortoise(`amqp://rudimk:YouKnowWhat@$localhost:5672`)
```
在导入`tortoise``node-cron` 我们继续并初始化了与RabbitMQ的连接。接下来让我们编写一个快速而脏的函数向Rabbit发布一条消息
```javascript
function scheduleMessage(){
let payload = {url: 'https://randomuser.me/api'}
tortoise
.exchange('random-user-exchange', 'direct', { durable:false })
.publish('random-user-key', payload)
}
```
这很简单。我们已经定义了一个字典,其中包含[RandomUser.me](https://randomuser.me/) API的URL然后使用`random-user-key`路由密钥将其发布到RabbitMQ上的`random-user-exchange`交换机。如前所述路由键是决定谁使用消息的方法。现在让我们编写一个调度规则每隔60秒发布一条消息。
```javascript
cron.schedule('60 * * * * *', scheduleMessage)
```
我们的出版商准备好了但是如果没有消费者真正消费这些消息真的没有用但首先我们需要一个可以在这些消息中调用URL的库。就个人而言我使用`superagent` `npm install --save superagent`
现在,在`consumer.js`
```javascript
const Tortoise = require('tortoise')
const superagent = require('superagent')
const tortoise = new Tortoise(`amqp://rudimk:YouKnowWhat@$localhost:5672`)
```
接下来让我们编写一个异步函数来调用URL并显示结果
```javascript
async function getURL(url){
let response = await superagent.get(url)
return response.body
}
```
编写实际消费消息的代码的时间:
```javascript
tortoise
.queue('random-user-queue', { durable: false })
// Add as many bindings as needed
.exchange('random-user-exchange', 'direct', 'random-user-key', { durable: false })
.prefetch(1)
.subscribe(function(msg, ack, nack) {
// Handle
let payload = JSON.parse(msg)
getURL(payload['url']).then((response) => {
console.log('Job result: ', response)
})
ack() // or nack()
})
```
在这里,我们告诉`tortoise`要监听`random-user-queue` ,该`random-user-queue``random-user-exchange`上的`random-user-exchange` `random-user-key`绑定。收到`msg` ,将从`msg`检索有效负载,并将其传递给`getURL`函数该函数将从RandomUser API返回带有所需JSON响应的Promise。
## 结论
与使用RabbitMQ进行消息传递相关的简单性是无与伦比的只需几行代码就可以很容易地得到非常复杂的微服务模式。最好的部分是消息传递背后的逻辑并没有真正改变语言--Crystal或Go或Python或Ruby以几乎相同的方式与Rabbit一起工作 - 这意味着您可以使用不同语言编写的服务可以毫不费力地相互通信,使您能够使用最好的语言来完成工作。

View File

@@ -0,0 +1,92 @@
---
title: Await Promises
localeTitle: 等待承诺
---
## 等待承诺
`async` / `await` [运算符](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators)可以更轻松地实现许多异步Promise。它们还允许工程师编写更清晰更简洁可测试的代码。
要理解这个主题,您应该对[Promise](https://guide.freecodecamp.org/javascript/promises)如何工作有充分的了解。
* * *
## 基本语法
\`\`\`\`javascript function slowlyResolvedPromiseFuncstring{ 返回新的Promiseresolve => { setTimeout=> { 解析(字符串); }5000; }; }
异步函数doIt{ const myPromise = await slowResolvedPromiseFunc“foo”; 的console.logmyPromise; //“foo” }
doIt方法;
```
There are a few things to note:
* The function that encompasses the `await` declaration must include the `async` operator. This will tell the JS interpreter that it must wait until the Promise is resolved or rejected.
* The `await` operator must be inline, during the const declaration.
* This works for `reject` as well as `resolve`.
---
## Nested Promises vs. `Async` / `Await`
Implementing a single Promise is pretty straightforward. In contrast, Chained Promises or the creation of a dependency pattern may produce "spaghetti code".
The following examples assume that the <a href='https://github.com/request/request-promise' target='_blank' rel='nofollow'>`request-promise`</a> library is available as `rp`.
### Chained/Nested Promises
```
JavaScript的 //第一承诺 const fooPromise = rp“http://domain.com/foo”;
fooPromise.thenresultFoo => { //必须等待“foo”才能解决 的console.logresultFoo;
```
const barPromise = rp("http://domain.com/bar");
const bazPromise = rp("http://domain.com/baz");
return Promise.all([barPromise, bazPromise]);
```
}。thenresultArr => { //在此处理“bar”和“baz”分辨率 的console.logresultArr \[0\]; 的console.logresultArr \[1\]; };
```
### `async` and `await` Promises
```
JavaScript的 //将所有内容包装在异步函数中 异步函数doItAll{ //从“foo”端点获取数据但等待解决 console.log等待rp“http://domain.com/foo”;
```
// Concurrently kick off the next two async calls,
// don't wait for "bar" to kick off "baz"
const barPromise = rp("http://domain.com/bar");
const bazPromise = rp("http://domain.com/baz");
// After both are concurrently kicked off, wait for both
const barResponse = await barPromise;
const bazResponse = await bazPromise;
console.log(barResponse);
console.log(bazResponse);
```
}
//最后,调用异步函数 doItAll。then=> console.log'Done';
```
The advantages of using `async` and `await` should be clear. This code is more readable, modular, and testable.
It's fair to note that even though there is an added sense of concurrency, the underlying computational process is the same as the previous example.
---
## Handling Errors / Rejection
A basic try-catch block handles a rejected Promise.
```
JavaScript的 异步函数errorExample{ 尝试{ const rejectedPromise = await Promise.reject“哦 - 哦!”); } catcherror{ 的console.log误差; //“呃 - 哦!” } }
errorExample; \`\`\`
* * *
#### 更多信息:
* `await`运营商[MDN文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await)
* `async`功能操作员[MDN文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/async_function)

View File

@@ -0,0 +1,102 @@
---
title: Boolean
localeTitle: 布尔
---
## 布尔
布尔值是计算机编程语言中常用的原始数据类型。根据定义,布尔值有两个可能的值: `true``false`
在Javascript中通常存在对boolean的隐式类型强制。例如如果你有一个if语句来检查某个表达式那么该表达式将被强制转换为布尔值
```javascript
var a = 'a string';
if (a) {
console.log(a); // logs 'a string'
}
```
只有少数值会被强制为false
* 假(不是真的被胁迫,因为它已经是假的)
* 空值
* 未定义
* 为NaN
* 0
* ''(空字符串)
所有其他值将被强制为true。 当一个值被强制转换为布尔值时,我们也称之为'falsy'或'truthy'。
使用类型强制的一种方法是使用or `||` 和and `&&` )运算符:
```javascript
var a = 'word';
var b = false;
var c = true;
var d = 0
var e = 1
var f = 2
var g = null
console.log(a || b); // 'word'
console.log(c || a); // true
console.log(b || a); // 'word'
console.log(e || f); // 1
console.log(f || e); // 2
console.log(d || g); // null
console.log(g || d); // 0
console.log(a && c); // true
console.log(c && a); // 'word'
```
如您所见, _or_运算符检查第一个操作数。如果这是真的或真实的它会立即返回这就是为什么我们在第一种情况下得到'word'而在第二种情况下得到true。如果它不是真或真它会返回第二个操作数这就是为什么我们在第三种情况下得到'word')。
使用和运算符它以类似的方式工作,但为了'和'是真的,两个操作数都需要真实。因此,如果两者都是真/真它将始终返回第二个操作数否则它将返回false。这就是为什么在第四种情况下我们得到了真实在最后一种情况下我们得到了'字'。
## 布尔对象
还有一个包含值的本机JavaScript对象。如有必要作为第一个参数传递的值将转换为布尔值。如果省略value0-0nullfalseNaNundefined或空字符串“”则对象的初始值为false。所有其他值包括任何对象或字符串“false”都会创建一个初始值为true的对象。
不要将原始布尔值true和false与布尔对象的true和false值混淆。
## 更多细节
任何值未定义或为null的对象包括值为false的Boolean对象在传递给条件语句时计算结果为true。如果为true则执行该函数。例如以下if语句中的条件求值为true
```javascript
var x = new Boolean(false);
if (x) {
// this code is executed
}
```
此行为不适用于布尔基元。例如以下if语句中的条件求值为false
```javascript
var x = false;
if (x) {
// this code is not executed
}
```
不要使用Boolean对象将非布尔值转换为布尔值。相反使用布尔值作为函数来执行此任务
```javascript
var x = Boolean(expression); // preferred
var x = new Boolean(expression); // don't use
```
如果指定任何对象包括值为false的Boolean对象作为Boolean对象的初始值则新的Boolean对象的值为true。
```javascript
var myFalse = new Boolean(false); // initial value of false
var g = new Boolean(myFalse); // initial value of true
var myString = new String('Hello'); // string object
var s = new Boolean(myString); // initial value of true
```
不要使用布尔对象代替布尔基元。
### 资源
* [布尔对象](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean)
* [布尔对象](https://docs.oracle.com/javase/7/docs/api/java/lang/Boolean.html)

View File

@@ -0,0 +1,80 @@
---
title: Callback Functions
localeTitle: 回调函数
---
本文简要介绍了Javascript编程语言中回调函数的概念和用法。
## 功能是对象
我们需要知道的第一件事是在Javascript中函数是一流的对象。因此我们可以像处理其他对象一样使用它们比如将它们分配给变量并将它们作为参数传递给其他函数。这很重要因为后一种技术允许我们在应用程序中扩展功能。
## 回调函数
**回调函数**是_作为参数_传递给另一个函数的函数以便稍后“回调”。接受其他函数作为参数的函数称为**高阶函数** 它包含回调函数执行_时_的逻辑。这两者的结合使我们能够扩展我们的功能。
为了说明回调,让我们从一个简单的例子开始:
```javascript
function createQuote(quote, callback){
var myQuote = "Like I always say, " + quote;
callback(myQuote); // 2
}
function logQuote(quote){
console.log(quote);
}
createQuote("eat your vegetables!", logQuote); // 1
// Result in console:
// Like I always say, eat your vegetables!
```
在上面的例子中, `createQuote`是高阶函数,它接受两个参数,第二个是回调。 `logQuote`函数用于传入我们的回调函数。当我们执行`createQuote`函数_1时_ 请注意当我们将它作为参数传递时我们_不会将_括号_附加_到`logQuote` 。这是因为我们不想立即执行我们的回调函数,我们只是想将函数定义传递给高阶函数,以便以后执行。
此外我们需要确保如果我们传入的回调函数需要参数那么我们在执行回调时提供这些参数_2_ 。在上面的例子中,那将是`callback(myQuote);`声明,因为我们知道`logQuote`需要传入引号。
另外,我们可以传递匿名函数作为回调。以下对`createQuote`调用与上面的示例具有相同的结果:
```javascript
createQuote("eat your vegetables!", function(quote){
console.log(quote);
});
```
顺便说一句你_不必_用“回拨”作为参数的名称使用Javascript只需要知道它是正确的参数名称。基于上面的例子下面的函数将以完全相同的方式运行。
```javascript
function createQuote(quote, functionToCall) {
var myQuote = "Like I always say, " + quote;
functionToCall(myQuote);
}
```
## 为什么要使用Callbacks
大多数时候,我们正在创建以**同步**方式运行的程序和应用程序。换句话说我们的一些操作只有在前面的操作完成后才会启动。通常当我们从其他来源例如外部API请求数据时我们并不总是知道_何时_会回送我们的数据。在这些情况下我们希望等待响应但我们并不总是希望我们的整个应用程序在获取数据时停止运行。这些情况是回调函数派上用场的地方。
我们来看一个模拟对服务器的请求的示例:
```javascript
function serverRequest(query, callback){
setTimeout(function(){
var response = query + "full!";
callback(response);
},5000);
}
function getResults(results){
console.log("Response from the server: " + results);
}
serverRequest("The glass is half ", getResults);
// Result in console after 5 second delay:
// Response from the server: The glass is half full!
```
在上面的示例中我们向服务器发出模拟请求。经过5秒后响应被修改然后我们的回调函数`getResults`被执行。要查看此操作,您可以将上述代码复制/粘贴到浏览器的开发人员工具中并执行它。
此外,如果您已经熟悉`setTimeout` ,那么您一直在使用回调函数。传递给上面例子的`setTimeout`函数调用的匿名函数参数也是一个回调函数!因此,示例的原始回调实际上是由另一个回调执行的。如果你可以帮忙的话,小心不要嵌套太多的回调,因为这会导致一种叫做“回调地狱”的东西!顾名思义,处理起来并不是一种乐趣。

View File

@@ -0,0 +1,174 @@
---
title: Classes
localeTitle: 类
---
## 类
JavaScript本身没有类的概念。
但是我们可以通过利用JavaScript的原型性质来模拟类的功能。
本文假设您对[原型](/src/pages/javascript/prototypes/index.md)有基本的了解。
为了清楚起见,我们假设我们想要创建一个可以执行以下操作的类
```javascript
var p = new Person('James','Bond'); // create a new instance of Person class
p.log() // Output: 'I am James Bond' // Accessing a function in the class
// Using setters and getters
p.profession = 'spy'
p.profession // output: James bond is a spy
```
### 使用class关键字
与任何其他编程语言一样,您现在可以使用`class`关键字来创建类。
旧版浏览器不支持此功能并且已在ECMAScript 2015中引入。
```javascript
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
log() {
console.log('I am', this._firstName, this._lastName);
}
// setters
set profession(val) {
this._profession = val;
}
// getters
get profession() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
}
```
`class`只是JavaScript现有的基于原型的继承模型的语法糖。
通常程序员使用以下方法在JavaScript中创建类。
### 使用添加到原型的方法:
在这里,所有方法都被添加到原型中
```javascript
function Person(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
Person.prototype.log = function() {
console.log('I am', this._firstName, this._lastName);
}
// This line adds getters and setters for the profession object. Note that in general you could just write your own get and set functions like the 'log' method above.
// Since in this example we are trying the mimic the class above, we try to use the getters and setters property provided by JavaScript
Object.defineProperty(Person.prototype, 'profession', {
set: function(val) {
this._profession = val;
},
get: function() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
})
```
您还可以在函数`Person`编写原型方法,如下所示
```javascript
Person.prototype = {
log: function() {
console.log('I am ', this._firstName, this._lastName);
}
set profession(val) {
this._profession = val;
}
get profession() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
}
```
### 使用内部添加的方法
这里的方法是内部添加而不是原型
```javascript
function Person(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
this.log = function() {
console.log('I am ', this._firstName, this._lastName);
}
Object.defineProperty(this, 'profession', {
set: function(val) {
this._profession = val;
},
get: function() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
})
}
```
### 用符号隐藏类中的细节
大多数情况下,必须隐藏一些属性和方法以防止从函数外部进行访问。对于类,要获得此功能,一种方法是使用符号。 Symbol是一种新的内置JavaScript类型可以调用它来提供新的符号值。每个符号都是唯一的可以用作对象的键。因此符号的一个用例是您可以向您可能不拥有的对象添加内容并且您可能不希望与对象的任何其他键冲突因此创建新的并使用符号将该属性添加到该对象是最安全的。此外当符号值添加到对象时;没有人会知道如何得到它。
```javascript
class Person {
constructor(firstName, lastName) {
this._firstName = firstName;
this._lastName = lastName;
}
log() {
console.log('I am', this._firstName, this._lastName);
}
// setters
set profession(val) {
this._profession = val;
}
// getters
get profession() {
console.log(this._firstName, this._lastName, 'is a', this._profession);
}
// With the above code, even though we can access the properties outside the function to change their content what if we don't want that.
// Symbols come to rescue.
let s_firstname = new Symbol();
class Person {
constructor(firstName, lastName) {
this[s_firstName] = firstName;
this._lastName = lastName;
}
log() {
console.log('I am', this._firstName, this._lastName);
}
// setters
set profession(val) {
this._profession = val;
}
// getters
get profession() {
console.log(this[s_firstName], this._lastName, 'is a', this._profession);
}
```
#### 更多信息:

View File

@@ -0,0 +1,177 @@
---
title: Closures
localeTitle: 关闭
---
# 关闭
闭包是函数和声明该函数的词法环境范围的组合。闭包是Javascript的基础和强大属性。本文讨论关闭闭包的'方式'和'原因'
### 例
```js
//we have an outer function named walk and an inner function named fly
function walk (){
var dist = '1780 feet';
function fly(){
console.log('At '+dist);
}
return fly;
}
var flyFunc = walk(); //calling walk returns the fly function which is being assigned to flyFunc
//you would expect that once the walk function above is run
//you would think that JavaScript has gotten rid of the 'dist' var
flyFunc(); //Logs out 'At 1780 feet'
//but you still can use the function as above
//this is the power of closures
```
### 另一个例子
```js
function by(propName) {
return function(a, b) {
return a[propName] - b[propName];
}
}
const person1 = {name: 'joe', height: 72};
const person2 = {name: 'rob', height: 70};
const person3 = {name: 'nicholas', height: 66};
const arr_ = [person1, person2, person3];
const arr_sorted = arr_.sort(by('height')); // [ { name: 'nicholas', height: 66 }, { name: 'rob', height: 70 },{ name: 'joe', height: 72 } ]
```
闭包'记住'创建它的环境。此环境由创建闭包时在范围内的任何局部变量组成。
```js
function outside(num) {
var rememberedVar = num; // In this example, rememberedVar is the lexical environment that the closure 'remembers'
return function inside() { // This is the function which the closure 'remembers'
console.log(rememberedVar)
}
}
var remember1 = outside(7); // remember1 is now a closure which contains rememberedVar = 7 in its lexical environment, and //the function 'inside'
var remember2 = outside(9); // remember2 is now a closure which contains rememberedVar = 9 in its lexical environment, and //the function 'inside'
remember1(); // This now executes the function 'inside' which console.logs(rememberedVar) => 7
remember2(); // This now executes the function 'inside' which console.logs(rememberedVar) => 9
```
闭包很有用因为它们让您“记住”数据然后让您通过返回的函数操作该数据。这允许javascript模拟其他编程语言中的私有方法。私有方法对于限制对代码的访问以及管理全局命名空间非常有用。
### 私有变量和方法
闭包还可用于封装私有数据/方法。看看这个例子:
```javascript
const bankAccount = (initialBalance) => {
const balance = initialBalance;
return {
getBalance: function() {
return balance;
},
deposit: function(amount) {
balance += amount;
return balance;
},
};
};
const account = bankAccount(100);
account.getBalance(); // 100
account.deposit(10); // 110
```
在这个例子中,我们将无法从`bankAccount`函数之外的任何地方访问`balance` ,这意味着我们刚刚创建了一个私有变量。封闭在哪里?好吧,想想`bankAccount()`正在返回什么。它实际上返回一个带有一堆函数的Object然而当我们调用`account.getBalance()` ,该函数能够“记住”它对`balance`初始引用。这就是闭包的强大功能,即函数“记住”它的词法范围(编译时范围),即使函数在该词法范围之外执行也是如此。
**模拟块范围的变量。**
Javascript没有块范围变量的概念。这意味着例如在forloop中定义变量时此变量也可以从forloop外部看到。那么闭包如何帮助我们解决这个问题呢让我们来看看。
```javascript
var funcs = [];
for(var i = 0; i < 3; i++){
funcs[i] = function(){
console.log('My value is ' + i); //creating three different functions with different param values.
}
}
for(var j = 0; j < 3; j++){
funcs[j](); // My value is 3
// My value is 3
// My value is 3
}
```
由于变量i没有块范围因此使用循环计数器更新了所有三个函数中的值并创建了恶意值。 Closure可以通过创建函数创建时的环境快照来帮助我们解决这个问题保留其状态。
```javascript
var funcs = [];
var createFunction = function(val){
return function() {console.log("My value: " + val);};
}
for (var i = 0; i < 3; i++) {
funcs[i] = createFunction(i);
}
for (var j = 0; j < 3; j++) {
funcs[j](); // My value is 0
// My value is 1
// My value is 2
}
```
javascript es6 +的后期版本有一个名为let的新关键字可用于为变量提供一个blockscope。 还有许多函数forEach和整个库lodash.js专门用于解决上述问题。它们当然可以提高您的工作效率但是在尝试创建大型项目时了解所有这些问题仍然非常重要。
闭包有许多特殊的应用程序在创建大型JavaScript程序时很有用。
1. 模拟私有变量或封装
2. 进行异步服务器端调用
3. 创建块范围的变量。
**模拟私有变量。**
与许多其他语言不同Javascript没有允许您在对象中创建封装实例变量的机制。在构建中型到大型程序时使用公共实例变量会导致很多问题。但是对于闭包可以减轻这个问题。
与前面的示例非常相似,您可以使用可以访问对象的局部变量的方法构建返回对象文字的函数,而不会暴露它们。因此,使它们实际上是私密的。
闭包还可以帮助您管理全局命名空间,以避免与全局共享数据冲突。通常,所有全局变量都在项目中的所有脚本之间共享,这在构建中型到大型程序时肯定会给您带来很多麻烦。这就是为什么库和模块作者使用闭包来隐藏整个模块的方法和数据的原因。这称为模块模式,它使用立即调用的函数表达式,该函数表达式仅将某些功能导出到外部世界,从而显着减少了全局引用的数量。
这是模块骨架的简短示例。
```javascript
var myModule = (function() = {
let privateVariable = 'I am a private variable';
let method1 = function(){ console.log('I am method 1'); };
let method2 = function(){ console.log('I am method 2, ', privateVariable); };
return {
method1: method1,
method2: method2
}
}());
myModule.method1(); // I am method 1
myModule.method2(); // I am method 2, I am a private variable
```
闭包对于捕获“记住的”环境中包含的私有变量的新实例很有用,并且这些变量只能通过返回的函数来访问。
### 更多信息:
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures)
[Javascript闭包](https://medium.freecodecamp.org/lets-learn-javascript-closures-66feb44f6a44)

View File

@@ -0,0 +1,35 @@
---
title: Code Block
localeTitle: 代码块
---
## 介绍
在计算机编程中, **块**或代码**块**是组合在一起的代码段。块由一个或多个声明和语句组成。允许创建块的编程语言(包括嵌套在其他块中的块)称为块结构编程语言。 JavaScript就是这样一种编程语言。
JavaScript中的**块**语句用于对零个或多个语句进行分组。该块由一对花括号分隔。
```
{
statement_1;
statement_2;
...
statement_n;
}
```
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block)
## 例子
**块**语句通常与控制流语句一起使用(例如, `if...else` `for` `while` )和函数。
```
while (x < 10) {
x++;
}
function addnums(num1, num2) {
var sum = 0;
sum = num1 + num2;
return sum;
}
```

View File

@@ -0,0 +1,25 @@
---
title: Code Linting
localeTitle: 代码Linting
---
Linting是运行程序的过程该程序分析代码中的程序和样式错误。 linting工具或linter标记或标记代码中的任何潜在错误例如语法错误或拼写错误的变量名称。这可以节省时间并帮助您编写更好的代码。
可以使用`npm`或其他包管理器安装`npm` 。可以通过传入文件从命令行使用Linters。 Linters也可用作工具的插件有时它们直接集成到编辑器中。
以下是一些流行的Javascript Linters
[JSLint的](http://www.javascriptlint.com/online_lint.php)
[JSHint](http://jshint.com)
[JSCS](http://jscs.info)
[ESLint](http://eslint.org)
#### 编辑Linters
* 可视代码要安装eslint扩展打开命令面板View - > Command Palette ..或cmd + shift + p并执行命令 ext install eslint
#### 工具和插件
[漂亮](https://prettier.io)

View File

@@ -0,0 +1,87 @@
---
title: Comments
localeTitle: 注释
---
## 注释
程序员使用注释向其源代码添加提示,注释,建议或警告;它们对代码的实际输出没有影响。注释可以非常有助于解释您的代码应该或应该做什么的意图。
在开始经常评论时,这总是最佳做法,因为它可以帮助那些阅读代码的人了解您的代码究竟打算做什么。
JavaScript有两种在代码中分配注释的方法。
第一种方式是`//`评论; `//`在同一行上的所有文字后面的注释。例如:
```javascript
function hello() {
// This is a one line JavaScript comment
console.log("Hello world!");
}
hello();
```
第二种方式是`/* */` comment它可以用于单行和多行注释。例如
```javascript
function hello() {
/* This is a one line JavaScript comment */
console.log("Hello world!");
}
hello();
```
```javascript
function hello() {
/* This comment spans multiple lines. Notice
that we don't need to end the comment until we're done. */
console.log("Hello world!");
}
hello();
```
您还可以阻止执行Javascript代码只需遵守这样的代码行
```javascript
function hello() {
/*console.log("Hello world!");*/
}
hello();
```
#### 更多信息:
[如何用JavaScript编写注释](https://www.digitalocean.com/community/tutorials/how-to-write-comments-in-javascript)
### 许多IDE都带有键盘快捷键来注释掉行。
1. 突出显示要评论的文本
2. Mac推送命令Apple Key“/”
3. Windows推送控制和“/”
4. 您也可以通过执行相同的步骤来取消注释代码
在许多代码编辑器中注释掉javascript部分的快捷方式是突出显示要注释掉的代码行然后按`Cmd/Ctrl + /`
注释对代码测试也非常有用,因为您可以阻止某个代码行/块运行
```javascript
function hello() {
// The statement below is not going to get executed
// console.log('hi')
}
hello();
```
```
function hello() {
// The statements below are not going to get executed
/*
console.log('hi');
console.log('code-test');
*/
}
hello();
```
#### 更多信息:
* [如何用JavaScript编写注释](https://www.digitalocean.com/community/tutorials/how-to-write-comments-in-javascript)

View File

@@ -0,0 +1,195 @@
---
title: Comparison Operators
localeTitle: 比较运算符
---
JavaScript具有**严格**和**类型转换**比较。
* 严格比较(例如===)仅在操作数类型相同时才为真。
* 更常用的抽象比较(例如==在进行比较之前将操作数转换为相同的Type。
* 对于关系抽象比较(例如,<=),操作数首先在比较之前转换为基元,然后转换为相同类型。
* 使用Unicode值基于标准词典排序比较字符串。
## 比较特点:
* 当两个字符串在相应位置具有相同的字符序列,相同的长度和相同的字符时,它们严格相等。
* 当两个数字在数值上相等(具有相同的数值)时,两个数字严格相等。 NaN不等于任何东西包括NaN。正负零彼此相等。
* 如果两个布尔操作数都为真或两者都为假,则它们严格相等。
* 对于严格或抽象的比较,两个不同的对象永远不会相等。
* 仅当操作数引用相同的Object时才会使用比较Objects的表达式。
* 空和未定义类型严格等于它们自己并且抽象地彼此相等。
## 平等运营商
### 平等(==
如果操作数**不是同一类型** ,则等于运算符会转换操作数,然后应用严格比较。如果**两个操作数都是对象** 则JavaScript比较内部引用当操作数引用内存中的同一对象时这些内部引用相等。
#### 句法
```
x == y
```
#### 例子
```
1 == 1 // true
"1" == 1 // true
1 == '1' // true
0 == false // true
0 == null // false
0 == undefined // false
null == undefined // true
```
### 不平等(!=
如果操作数不相等则不等运算符返回true。如果两个操作数**的类型不同** 则JavaScript会尝试将操作数转换为适当的类型以进行比较。如果**两个操作数都是对象** 则JavaScript比较内部引用当操作数引用内存中的不同对象时这些引用不相等。
#### 句法
```
x != y
```
#### 例子
```
1 != 2 // true
1 != "1" // false
1 != '1' // false
1 != true // false
0 != false // false
```
### 身份/严格平等(===
如果操作数严格相等**而没有类型转换,**则identity运算符返回true。
#### 句法
```
x === y
```
#### 例子
```
3 === 3 // true
3 === '3' // false
```
### 非身份/严格不平等(!==
如果操作数**不相等和/或不是相同类型,则**非标识运算符返回true。
#### 句法
```
x !== y
```
#### 例子
```
3 !== '3' // true
4 !== 3 // true
```
## 关系运算符
### 大于运算符(>
如果左操作数大于右操作数则大于运算符返回true。
#### 句法
```
x > y
```
#### 例子
```
4 > 3 // true
```
### 运算符大于等于(> =
如果左操作数大于或等于右操作数则大于或等于运算符返回true。
#### 句法
```
x >= y
```
#### 例子
```
4 >= 3 // true
3 >= 3 // true
```
### 小于运算符(<
如果左操作数小于右操作数则小于运算符返回true。
#### 句法
```
x < y
```
#### 例子
```
3 < 4 // true
```
### 小于等于运算符(<=
如果左操作数小于或等于右操作数则小于或等于运算符返回true。
#### 句法
```
x <= y
```
#### 例子
```
3 <= 4 // true
```
_您可以在[MDN上](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)找到更多信息。_
## 比较null和undefined
当我们比较null和undefined时我们会看到不同的行为。让我们通过示例检查不同的场景
#### 示例 - 严格相等检查(===
console.lognull === undefined; // O / P - 假
Otuput是假的这是正确的因为我们知道“null”和“undefined”是不同的类型。
#### 示例 - 非严格相等性检查(==
console.lognull == undefined; // O / P - 是的
怎么样这是因为“null”和“undefined”有一个特殊规则。由于它们在非严格检查==)的情况下是相同的,但不等于任何其他值。
如果我们使用比较运算符,如<><=> =等则“null”和“undefined”将转换为数字在这种情况下“null”将变为0“undefined”将为NaN。让我们检查一下这些例子。
#### 示例 - 将null与0进行比较
console.lognull> 0; // O / P - 假 console.lognull> = 0; // O / P - 是的 console.lognull == 0; // O / P - 假
奇怪根据第一个语句null不大于0并且从第二个语句中null大于或等于0.因此如果我们以数学方式思考并比较两个语句则会得到null等于0的结果。 ,按照第三种说法,这不是真的。为什么?
原因是“比较”和“平等检查”都以不同的方式起作用。 相比之下“null / undefined”首先转换为数字因此在前两种情况下“null”变为0因此case1null> 0 - > false和case2null> = 0 - > true。 但是,在等式检查(==“null / undefined”在没有任何转换的情况下工作并且如上所述特殊规则在等式检查中“null / undefined”仅相互等于并且不等于其他任何内容。因此null == 0 - > false。
#### 示例 - 将undefined与0进行比较
console.logundefined> 0; // O / P - 假 console.logundefined> = 0; // O / P - 假 console.logundefined == 0; // O / P - 假
在这里我们测试与null相同的情况但结果又不同。为什么
原因如下。 在前两种情况下我们将undefined与0进行比较并且如上所述比较undefined会转换为NaN。 NaN是一个特殊值与任何数字相比总是返回false这就是我们在前两种情况下输出为false的原因。 对于第三个陈述原因与“null”中提到的相同。在等式检查中“null / undefined”仅相互等于并且不等于其他任何内容。因此undefined == 0 - > false。

View File

@@ -0,0 +1,66 @@
---
title: Concurrency Model and Event Loop
localeTitle: 并发模型和事件循环
---
## 并发模型和事件循环
Javascript运行时是单线程的这意味着它可以一次执行一段代码。为了理解Javascript中的并发模型和事件循环我们必须首先解决与之相关的一些常见术语。首先让我们了解什么是调用堆栈。
调用堆栈是一种简单的数据结构,它记录了我们当前代码中的位置。因此,如果我们进入一个函数调用函数,它将被推送到调用堆栈,当我们从函数返回时,它会从堆栈中弹出。
让我们用一个代码示例来理解调用栈 -
```javascript
function multiply(x,y) {
return x * y;
}
function squared(n) {
return multiply(n,n)
}
function printSquare(n) {
return squared(n)
}
let numberSquared = printSquare(5);
console.log(numberSquared);
```
首先,当代码执行时,运行时将读取每个函数定义,但是当它到达调用第一个函数**printSquare5**的行时,它会将此函数推送到调用堆栈中。接下来,此函数将执行并在返回之前将遇到另一个函数**平方n**因此它将暂停其当前操作并将此函数推送到现有函数之上。它在这种情况下执行函数平方函数,最后遇到另一个函数**multiplynn**因此它暂停当前执行并将此函数推入调用堆栈。函数 乘法执行并以相乘的值返回。最后平方函数返回并从堆栈弹出然后与printSquare相同。最终的平方值被分配给numberSquared变量。我们再次遇到函数调用在这种情况下它是一个console.log语句因此运行时将其推送到执行它的堆栈从而在控制台上打印平方数字。应该注意的是在上述任何代码运行之前被推入堆栈的第一个函数是主函数它在运行时被表示为“匿名函数”。
因此,无论何时调用函数,它都会被推送到执行它的调用堆栈中。最后,当函数完成它的执行并且隐式或显式返回时,它将从堆栈中弹出。调用堆栈只记录函数执行的时间点。它跟踪当前正在执行的功能。
现在我们知道Javascript可以一次执行一件事但是浏览器不是这样。浏览器拥有自己的一组API如setTimeoutXMLHttpRequests它们未在Javascript运行时中指定。事实上如果你仔细查看V8的源代码那么为谷歌Chrome浏览器提供支持的流行Javascript运行时你将找不到任何定义。这是因为这些特殊的Web API存在于浏览器环境中而不是javascript环境中你可以说这些apis引入了并发性。让我们看一个图来理解整个图片。
![并发和事件循环模型](https://i.imgur.com/rnQEY7o.png)
引入了更多术语
**堆** - 它主要是分配对象的地方。
**回调队列** - 这是一个存储所有回调的数据结构。因为它是一个队列所以元素是基于先进先出的FIFO处理的。
**事件循环** - 这是所有这些事情汇集在一起​​的地方。事件循环简单地做的是检查调用堆栈,如果它是空的,这意味着堆栈中没有函数,它从最旧的回调来自 回调队列并将其推入调用堆栈,最终执行回调。
让我们用代码示例来理解这一点 -
```javascript
console.log('hi');
setTimeout(function() {
console.log('freecodeCamp')
},5000);
console.log('JS')
```
当第一行执行时它是一个console.log这是一个函数调用这意味着这个函数被推入调用堆栈在那里它执行打印'hi'到控制台最后它被返回并从堆栈中弹出。然后当运行时执行setTimeout它知道这是一个Web API因此它将它交给浏览器来处理它的执行。浏览器启动计时器然后JS运行时将setTimeout弹出堆栈。它遇到另一个console.log调用所以它将它推入调用堆栈消息'JS'被记录到控制台然后它最终返回所以最后一个console.log从堆栈中弹出。现在调用堆栈是空的。与此同时虽然所有这一切都在计时器结束即5秒后浏览器继续并将回调函数推送到回调队列。接下来事件循环检查调用堆栈是否空闲。由于它是自由的它接受回调函数并再次将其推回到执行其中的代码的调用堆栈。再次在代码内部有一个console.log调用所以这个函数进入堆栈的顶部执行它将'freecodecamp'记录到控制台中,最后返回,这意味着它从堆栈中弹出,最后回调被弹出堆栈,我们完成了。
为了更好地想象这一点请使用Phillip Roberts- [Loupe Event Loop Visualizer来](http://latentflip.com/loupe/?code=!!!PGJ1dHRvbj5DbGljayBtZSE8L2J1dHRvbj4%3D)尝试这个工具
#### 更多信息:
[菲利普罗伯茨:无论如何,事件循环到底是什么? | JSConf EU 2014](https://www.youtube.com/watch?v=8aGhZQkoFbQ)
[并发模型和事件循环MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop)

View File

@@ -0,0 +1,37 @@
---
title: Conditional Ternary Operators
localeTitle: 条件三元运算符
---
## 条件三元运算符
### 基本用法
三元运算符是在表达式中编写if-else的紧凑方法。
```js
const thing = (condition) ? <if true> : <if false>;
```
例如
```js
const cappedInput = input > 50 ? 50 : input // this will cap the input at 50
```
### 否则,如果
你也可以链接三元运算符这样你就会有一个if-else if-else行为
```js
<first condition> ? <value if first true>
: <second condition> ? <value if second is true>
: <fallback value>
```
> **专业提示** :如您所见,您可以在多行上拆分三元运算符 例如
```
const wealth = housesOwned > 3 ? "rich"
: housesOwned > 1 ? "nothing to complain"
: "poor"
```

View File

@@ -0,0 +1,99 @@
---
title: Converting Strings to Numbers
localeTitle: 将字符串转换为数字
---
## 将字符串转换为数字
`parseInt()`函数解析字符串参数并返回指定基数的整数(数学系统中的基数)。
```js
parseInt(string, radix);
```
### 参数
```
string
```
要解析的值。如果`string`参数不是字符串,则将其转换为字符串(使用`ToString`抽象操作)。字符串参数中的前导空格被忽略。'= 基数 2到36之间的整数表示上述字符串的基数数学数字系统中的基数。为人类常用的十进制数字系统指定`10` 。始终指定此参数以消除读者混淆并保证可预测的行为。当未指定基数时不同的实现会产生不同的结果通常将值默认为10。 返回值 从给定字符串解析的整数。如果第一个字符无法转换为数字,则返回`NaN`
### 描述
`parseInt`函数将其第一个参数转换为字符串,对其进行解析,并返回一个整数或`NaN` 。如果不是`NaN` 则返回的值将是作为指定基数基数中的数字的第一个参数的整数。例如10的基数表示从十进制数8八进制16十六进制等转换。对于大于`10`的基数字母表中的字母表示大于9的数字。例如对于十六进制数字基数16使用`A``F`
如果`parseInt`遇到的字符不是指定基数中的数字,它会忽略它和所有后续字符,并返回解析到该点的整数值。 `parseInt`将数字截断为整数值。允许前导和尾随空格。
由于某些数字在其字符串表示中包含`e`字符(例如`6.022e23` ),因此使用`parseInt`截断数值会在非常大或非常小的数字上使用时产生意外结果。 `parseInt`不应该用作`Math.floor()`的替代品。
如果radix `undefined`或0或不存在则JavaScript假定以下内容
* 如果输入`string`以“0x”或“0X”开头则基数为16十六进制并解析字符串的其余部分。
* 如果输入`string`以“0”开头则基数为八八进制或10十进制。究竟选择哪个基数是依赖于实现的。 ECMAScript 5指定使用10十进制但并非所有浏览器都支持此功能。因此在使用parseInt时始终指定基数。
* 如果输入`string`以任何其他值开头则基数为10十进制
* 如果第一个字符无法转换为数字则parseInt返回NaN。
出于算术目的NaN值不是任何基数中的数字。您可以调用isNaN函数来确定parseInt的结果是否为NaN。如果将NaN传递给算术运算则运算结果也将是NaN。
要将数字转换为特定基数中的字符串文字请使用intValue.toStringradix
### 例子
使用`parseInt` 以下示例均返回`15`
```js
parseInt(' 0xF', 16);
parseInt(' F', 16);
parseInt('17', 8);
parseInt(021, 8);
parseInt('015', 10); // parseInt(015, 10); will return 15
parseInt(15.99, 10);
parseInt('15,123', 10);
parseInt('FXX123', 16);
parseInt('1111', 2);
parseInt('15 * 3', 10);
parseInt('15e2', 10);
parseInt('15px', 10);
parseInt('12', 13);
```
以下示例均返回`NaN`
```js
parseInt('Hello', 8); // Not a number at all
parseInt('546', 2); // Digits are not valid for binary representations
```
以下示例都返回`-15`
```js
parseInt('-F', 16);
parseInt('-0F', 16);
parseInt('-0XF', 16);
parseInt(-15.1, 10)
parseInt(' -17', 8);
parseInt(' -15', 10);
parseInt('-1111', 2);
parseInt('-15e1', 10);
parseInt('-12', 13);
```
以下示例均返回`4`
```js
parseInt(4.7, 10);
parseInt(4.7 * 1e22, 10); // Very large number becomes 4
parseInt(0.00000000000434, 10); // Very small number becomes 4
```
以下示例返回`224`
```js
parseInt('0e0', 16);
```
#### 更多信息:
[MDN上的parseInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators)
* [parseInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt)和[parseFloat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat)尝试将字符串转换为数字(如果可能)。例如, `var x = parseInt("100"); // x = 100`
* [Number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/number)将转换为值可以表示的数字。这包括自UTC时间1970年1月1日午夜以来的毫秒数布尔值为1或0的日期以及无法转换为可识别数字的值将变为NaN。这代表Not a Number在技术上也是一个数字

View File

@@ -0,0 +1,156 @@
---
title: Error Handling and Try Catch Throw
localeTitle: 错误处理和尝试抓住投掷
---
## 错误处理和尝试抓住投掷
`try...catch..finally`语句标记要尝试的语句块,并指定响应,如果抛出异常。 `try`语句包含一个或多个语句,以及至少一个`catch`子句或`finally`子句,或两者。
#### `try...catch`
```javascript
try {
throw new Error('my error');
}
catch (e) {
console.error(e.message);
}
// Output:
// my error
```
#### `try...finally`
```javascript
try {
throw new Error('my error');
}
finally {
console.error('finally');
}
// Output:
// finally
```
_注意_当你没有`catch`到错误时,它实际上并没有被“ `catch` ”,即使执行了`finally`块。这意味着错误将继续到上面的`try`块(或主块)。
#### `try...catch...finally`
```javascript
try {
throw new Error('my error');
}
catch (e) {
console.error(e.message);
}
finally {
console.error('finally');
}
// Output:
// my error
// finally
```
典型用法:
```javascript
try {
openFile(file);
readFile(file)
}
catch (e) {
console.error(e.message);
}
finally {
closeFile(file);
}
```
#### 嵌套`try...catch`
你也可以:
*`try`块中嵌入`try-catch`语句。
* 向上抛出错误。
```javascript
try {
try {
throw new Error('my error');
}
catch (e) {
console.error('inner', e.message);
throw e;
}
finally {
console.log('finally');
}
}
catch (e) {
console.error('outer', e.message);
}
// Output:
// inner my error
// finally
// outer my error
```
#### 错误类型
##### 参考错误
```javascript
var x;
try {
x = y + 1; // y cannot be referenced (used)
}
catch(err) {
console.log(err.name, err.message);
}
// ReferenceError y is not defined
```
##### 语法错误
```javascript
try {
eval("alert('Hello)"); // Missing ' will produce an error
}
catch(err) {
console.log(err.name,err.message);
}
// SyntaxError Invalid or unexpected token
```
##### 输入错误
```javascript
var num = 1;
try {
num.toUpperCase(); // You cannot convert a number to upper case
}
catch(err) {
console.log(err.name, err.message);
}
// TypeError num.toUpperCase is not a function
```
##### URI错误
```javascript
try {
decodeURI("%%%"); // You cannot URI decode these percent signs
}
catch(err) {
console.log(err.name, err.message);
}
// URIError URI malformed
```
#### 更多信息:
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try…catch) [W3S](https://www.w3schools.com/js/js_errors.asp)

View File

@@ -0,0 +1,61 @@
---
title: Arrow Functions
localeTitle: 箭头功能
---
## 箭头功能
ES6中的功能发生了一些变化。我的意思是语法。
```javascript
// Old Syntax
function oldOne() {
console.log("Hello World..!");
}
// New Syntax
var newOne = () => {
console.log("Hello World..!");
}
```
新语法可能会让人感到困惑。但我会尝试解释语法。 语法分为两部分。
1. var newOne =
2. \=> {}
第一部分是声明一个变量并将函数(即)()分配给它。它只是说变量实际上是一个函数。
然后第二部分声明函数的正文部分。带有花括号的箭头部分定义了身体部位。
参数的另一个例子:
```javascript
let NewOneWithParameters = (a, b) => {
console.log(a+b); // 30
}
NewOneWithParameters(10, 20);
```
当只有一个参数名称时,括号是可选的:
```javascript
let newOneWithOneParam = a => {
console.log(a);
}
```
箭头功能的一个令人难以置信的优点是你不能重新绑定箭头功能。它将始终使用定义它的上下文进行调用。只需使用正常功能。
```javascript
// Old Syntax
axios.get(url).then(function(response) {
this.data = response.data;
}).bind(this);
// New Syntax
axios.get(url).then(response => {
this.data = response.data;
});
```
我认为我不需要对此作出解释。这很简单。

View File

@@ -0,0 +1,45 @@
---
title: Default Parameters
localeTitle: 默认参数
---
## 默认参数
如果您熟悉RubyPython等其他编程语言那么默认参数对您来说并不陌生。
默认参数是在声明函数时默认给出的参数。但是在调用函数时可以更改它的值。
```
let Func = (a, b = 10) => {
return a + b;
}
Func(20); // 20 + 10 = 30
```
在上面的例子中,我们只传递一个参数。该函数使用默认参数并执行该函数。
考虑另一个例子:
```
Func(20, 50); // 20 + 50 = 70
```
在上面的示例中,该函数采用两个参数,第二个参数替换默认参数。
考虑另一个例子:
```
let NotWorkingFunction = (a = 10, b) => {
return a + b;
}
NotWorkingFunction(20); // NAN. Not gonna work.
```
当您使用参数调用函数时,它们将按顺序分配。 (即)第一个值分配给第一个参数,第二个值分配给第二个参数,依此类推。
在上面的例子中值20被赋值给参数'a'而'b'没有任何值。所以我们没有得到任何输出。
但,
```
NotWorkingFunction(20, 30); // 50;
```
工作正常。

View File

@@ -0,0 +1,65 @@
---
title: Destructuring Assignment
localeTitle: 解构分配
---
## 解构分配
Destructuring Assignment语法是一个Javascript表达式可以从数组或对象中解压缩值或属性。
假设您有一个包含名字和姓氏的数组因为它是两个值但您希望将这些值重新分配给更具描述性的值。您可以使用Destructuring来完成此任务。
**ES5解构**
```js
var fullName = ["John", "Smith"];
var firstName = fullName[0];
var lastName = fullName[1];
console.log(firstName, lastName); // John Smith
```
**ES6解构**
```js
const fullName = ["John", "Smith"];
const [firstName, lastName] = fullName;
console.log(firstName, lastName); // John Smith
```
上面的示例显示了使用ES6 Destructuring Assignment的好处。
您还可以使用类似语法在对象上使用Destructuring
```js
const fullName = { first: "John", last: "Smith"};
const {first, last} = fullName;
console.log(first, last); // John Smith
```
对象解析分配略有不同,因为对象必须具有您要分配的名称的属性。因此,下面的代码不会按预期工作。
```js
const fullName = { first: "John", last: "Smith"};
const {firstName, lastName} = fullName;
console.log(firstName, lastName); // undefined undefined
```
您仍然可以使用以下语法获得所需的结果。
```js
const obj = {propertyName: value}
{propertyName: desiredVariableName} = obj
```
我们之前的例子将被重写如下:
```js
const fullName = { first: "John", last: "Smith"};
const {first: firstName, last: lastName} = fullName;
console.log(firstName, lastName); // John Smith
```

View File

@@ -0,0 +1,99 @@
---
title: for-of loop
localeTitle: for-of循环
---
## for-of Loop
for-of循环可用于迭代不是数组但可迭代的东西如DOM集合字符串集合参数或映射。
```javascript
const fruits = ['Orange','Apple','Grapes','Banana'];
for (const fruit of fruits)
{
console.log(fruit);
}
```
上面的代码片段将返回上面数组中的项目。
## 了解索引的for-of循环
如果我们想知道每个项目的索引怎么办。在这种情况下我们可以遍历fruits.entries它给我们ArrayIterator。
```javascript
for (const fruit of fruits.entries())
{
console.log(fruit);
}
```
在上面的代码片段中水果将是一个包含两个项目的数组。第0项将包含索引第1项将包含实际的水果名称。输出将如下
```
[0, "Orange"]
[1, "Apple"]
[2, "Grapes"]
[3, "Banana"]
```
我们可以进一步解构如下的水果:
```javascript
for (const [index,fruit] of fruits.entries())
{
console.log(index,fruit);
}
```
## for-of循环迭代未知数量的参数
for-of循环非常有助于迭代函数的未知数量的参数。
假设我们想要添加传递给函数的数字,并且参数的数量不固定。
'arguments'是javascript中的一个特殊关键字它为我们提供了Array-ish非数组类型并为我们提供了所有参数。
```javascript
function addNumbers()
{
let sum = 0;
for (const num of arguments)
sum+=num;
return sum;
}
addNumbers(1, 2, 3, 4, 5); // 15
```
这里的参数不是一个真正的数组我们仍然可以使用for-of循环迭代它。
## for-of循环迭代字符串
我们可以使用for-of循环来迭代字符串以便按字符串的字符给出字符。
```javascript
const name = 'John Doe';
for (const char of name)
console.log(char);
```
这导致以下输出: 字符'J''o''h''n''''D''o''e'
## for-of循环迭代DOM集合
DOM集合不是真正的数组类型。它们通常是大多数浏览器的NodeList。如果我们创建了许多段落并希望迭代它们以在每个段落上分配一些事件我们可以使用for-of循环。
```javascript
const paragraphs = document.querySelectorAll('p');
```
这里的段落是一个NodeList它可以使用for-of循环进行迭代。
```javascript
for (const para of paragraphs)
{
console.log(para);
// We can add event listeners to each para here
}

View File

@@ -0,0 +1,58 @@
---
title: ES6
localeTitle: ES6
---
## ES6
第6版ECMAScript称为ES6。
它也被称为ES2015。
这些更改增加了许多语法糖,允许开发人员以面向对象的方式创建应用程序。
> ES5示例
```javascript
var User = function () {
function User(name) {
this._name = name;
}
User.prototype.getName = function getName(x) {
return 'Mr./Mrs. ' + this._name;
};
return User;
}();
```
> ES6示例
```javascript
class User {
constructor(name) {
this._name = name
}
getName() {
return `Mr./Mrs. ${this._name}`
}
}
```
引入了许多新的语法功能,包括:
* 类,
* 模块,
* 模板,
* for / of循环
* 生成器表达式
* 箭头功能,
* 收藏,
* 承诺。
如今,大多数功能都可以在所有流行的浏览器中使用。 [兼容性表](https://kangax.github.io/compat-table/es6/)包含有关所有现代浏览器的功能可用性的所有信息。
经常出现新功能这是继承者ES7的一部分。一种常见的方法是将现代JavaScriptES6ES7和其他实验方案翻译成ES5。这确保了旧浏览器也可以执行代码。像[Babel](https://babeljs.io/)这样的工具可以将新的JavaScript转换为ES5。
除了来自ECMAScript标准的语法糖之外还有一些需要[Polyfill的功能](https://babeljs.io/docs/usage/polyfill) 。通常它们是必需的,因为整个类/方法实现被添加到标准中。

View File

@@ -0,0 +1,52 @@
---
title: Let and Const
localeTitle: 让和Const
---
## 让
let类似于var但是有范围。 let只能在定义的块级别中访问。
```
if (true) {
let a = 40;
console.log(a); //40
}
console.log(a); // undefined
```
在上面的示例中,变量'a'在If语句中定义因此在函数外部无法访问。
另一个例子:
```
let a = 50;
let b = 100;
if (true) {
let a = 60;
var c = 10;
console.log(a/c); // 6
console.log(b/c); // 10
}
console.log(c); // 10
console.log(a); // 50
```
## 常量
Const用于为变量赋值常量。价值无法改变。这是固定的。
```
const a = 50;
a = 60; // shows error. You cannot change the value of const.
const b = "Constant variable";
b = "Assigning new value"; // shows error.
```
考虑另一个例子。
```
const LANGUAGES = ['Js', 'Ruby', 'Python', 'Go'];
LANGUAGES = "Javascript"; // shows error.
LANGUAGES.push('Java'); // Works fine.
console.log(LANGUAGES); // ['Js', 'Ruby', 'Python', 'Go', 'Java']
```
这可能有点混乱。
以这种方式考虑。无论何时定义const变量Javascript都会将值的地址引用给变量。在我们的示例中变量'LANGUAGES'实际上引用了分配给数组的内存。因此,您无法在以后更改变量以引用其他内存位置。在整个程序中它只引用数组。

View File

@@ -0,0 +1,25 @@
---
title: Map Function
localeTitle: 地图功能
---
## 地图功能
`map()`函数用于从现有数组创建新数组,将函数应用于第一个数组的每个元素。
map函数的原始语法是
```javascript
let new_arr = arr.map(function callback(currentValue, index, array) {
// Do some stuff with currentValue (index and array are optionals)
})
```
### 示例ES6
```javascript
const myArray_1 = [1, 2, 3, 4];
const myArray_2 = myArray_1.map(el => el * 2);
```
`myArray_2`将包含以下元素: `[2, 4, 6, 8]`

View File

@@ -0,0 +1,62 @@
---
title: New String Functions
localeTitle: 新的字符串函数
---
## 新的字符串函数
以下四个函数在ES6中添加了新的字符串。
* 以。。开始
* 以。。结束
* 包括
* 重复
## 以。。开始:
这是一个区分大小写的函数,它可以帮助我们查找特定字符串是否以某个子字符串开头。
startsWith接受名为position的第二个可选参数当我们想要在搜索之前从字符串的开头跳过特定数量的字符时我们可以使用它。
```javascript
const str ='Rachna';
str.startsWith('Rad') //false
str.startsWith('ra') //false as it is case sensitive
str.startsWith('Ra') //true
str.startsWith('ch',2) //true as we are searching from the second position
str.startsWith('ch',3) //false
```
## 以。。结束
这是一个区分大小写的函数,它可以帮助我们查找特定字符串是否以某个子字符串结尾。
endsWith接受一个名为endPosition的第二个可选参数我们可以使用它来包含搜索前的字符数。
```javascript
const city= 'Delhi';
city.endsWith('Hi'); //false as it is case sensitive
city.endsWith('hi');//true
city.endsWith('l',3);//true - include only first three characters before searching
city.endsWith('l',4);//false
```
## 包括
includes函数也是一个区分大小写的函数用于检查searchString是否存在于字符串中的任何位置。
```javascript
const name='John Doe';
name.includes('do'); //false
name.includes('D'); //true
name.includes('Do'); //true
```
## 重复
重复允许我们取一个字符串并重复多次。
```javascript
const str = 'This is repeated';
str.repeat(3); //"This is repeatedThis is repeatedThis is repeated"
```

View File

@@ -0,0 +1,25 @@
---
title: Some Function
localeTitle: 一些功能
---
## 一些功能
`some()`函数用于验证数组中是否至少有一个元素满足给定条件。如果条件由一个元素满足,则该函数返回`true`如果任何元素满足条件则返回false
某些函数的原始语法是:
```javascript
arr.some(function callback(currentValue, index, array) {
// Do some stuff with currentValue (index and array are optionals)
}, [thisArg]);
```
### 示例ES6
```javascript
const arr = [1, 4, 5, 11];
if (arr.some(el => el % 2 == 0)) {
console.log("There's at least one even number");
}
```

View File

@@ -0,0 +1,23 @@
---
title: Spread Operator
localeTitle: 传播运营商
---
## 传播运营商
扩展运算符( `...` )允许获取集合的元素。
最常见的用途之一是`Node` Objects当在浏览器中使用查询选择器时为了使它们成为可迭代的数组对象
```javascript
const paragraphs = document.querySelectorAll('p.paragraph');
const arr = [...paragraphs];
```
扩展运算符的另一个用途是用于数组连接:
```javascript
const arr_1 = [1, 2, 3, 4]
const arr_2 = [5, 6, 7, 8]
const arr_final = [...arr_1, ...arr_2]
// arr_final = [1, 2, 3, 4, 5, 6, 7, 8]

View File

@@ -0,0 +1,76 @@
---
title: Template Literals
localeTitle: 模板文字
---
## 模板文字
## 介绍:
当我们想使用变量来创建一个字符串时,它变得非常痛苦,因为我们必须使用+符号来连接和跟踪引号。
现在使用ES6我们可以使用反引号和使用带有美元符号和花括号的占位符来创建字符串例如$ {expression}。
```javascript
const name='John';
const city='London';
Older Style:
const sentence ='My name is '+ name +'. I live in '+city.
ES6 way:
const sentence = `My name is ${name}. I live in ${city}`;
Here ${name} and ${city}are going to be interpolated by the variable name and city respectively.
```
## MultiLine字符串
旧款式:
当我们想要将字符串跨越到多行时,我们不得不使用反斜杠。
```javascript
const multipleLineString= "We have \
multiple lines \
here";
```
现在当我们想要创建多行字符串时我们可以使用模板字符串。我们可以使用反引号来包围我们的字符串。当我们想要创建一些动态html标记时这种方法非常有用。
```javascript
const htmlMarkup = `
<html>
<head></head>
<title>Template string</title>
<body>Hello World</body>
</html>`;
```
## 嵌套模板字符串:
我们可以将它们嵌套在一起。
```javascript
const cities =[
{name:'Delhi', year: 2010},
{name:'Mumbai', year: 2015},
{name:'Kolkata', year: 2017}];
const markup = `
<ul>
${cities.map(city=>`<li>I lived in ${city.name} in the year ${city.year}</li>`).join('')}
</ul>`;
```
这里map函数之后的join运算符删除了每个li之后添加的额外逗号。
## 如果声明和功能
我们也可以在模板字符串中使用If语句。
```javascript
const data = {name: 'John', city: 'London', birthyear: 1900};
const markup = `<div>${data.name} lives in ${data.city}. ${data.birthyear ? `<div>He was born in the year ${data.birthyear}</div>`:''}</div>`;
```
在上面的例子中如果定义了birthyear那么生成内容为“他出生在一年中”的div否则将不会创建div。

View File

@@ -0,0 +1,74 @@
---
title: Falsy Values
localeTitle: 虚假的价值观
---
## 描述
虚假值是评估为FALSE的值例如在检查变量时。 JavaScript中只有六个falsey值 `undefined` `null` `NaN` `0` `""` (空字符串),当然还有`false`
## 检查变量上的假值
可以使用简单的条件检查变量中的假值:
```javascript
if (!variable) {
// When the variable has a falsy value the condition is true.
}
```
## 一般例子
```javascript
var string = ""; // <-- falsy
var filledString = "some string in here"; // <-- truthy
var zero = 0; // <-- falsy
var numberGreaterThanZero // <-- truthy
var emptyArray = []; // <-- truthy, we'll explore more about this next
var emptyObject = {}; // <-- truthy
```
## 有阵列的乐趣
```javascript
if ([] == false) // <-- truthy, will run code in if-block
if ([]) // <-- truthy, will also run code in if-block
if ([] == true) // <-- falsy, will NOT run code in if-block
if (![]) // <-- falsy, will also NOT run code in if-block
```
## 警告
在布尔上下文中评估值时请注意数据类型。如果值的数据类型是一个_数字_ 那么truthy / falsy评估可能会导致意外的结果
```javascript
const match = { teamA: 0, teamB: 1 }
if (match.teamA)
// The following won't run due to the falsy evaluation
console.log('Team A: ' + match.teamA);
}
```
上面用例的替代方法是使用`typeof`评估值:
```javascript
const match = { teamA: 0, teamB: 1 }
if (typeof match.teamA === 'number')
console.log('Team A: ' + match.teamA);
}
```
## 更多信息
* **真实的** [博客文章 - TruthyFalsey](http://james.padolsey.com/javascript/truthy-falsey/)
* [Falsy |词汇表| MDN](https://developer.mozilla.org/en-US/docs/Glossary/Falsy)
* [Truthy和Falsy当JavaScript中的所有不相等时](https://www.sitepoint.com/javascript-truthy-falsy/)

View File

@@ -0,0 +1,179 @@
---
title: Form Validation
localeTitle: 表格验证
---
## 表格验证
在客户端输入所有必要数据然后按下“提交”按钮后,通常用于在服务器上进行的表单验证。如果数据 客户输入的内容不正确或只是丢失,服务器必须将所有数据发送回客户端并请求表单 重新提交正确的信息。这真是一个漫长的过程,曾经给服务器带来了很多负担。
JavaScript提供了一种在将客户端计算机上的数据发送到Web服务器之前验证其数据的方法。表单验证通常执行两次 功能:
### 基本验证
首先,必须检查表单以确保填写所有必填字段。它只需要循环遍历表单中的每个字段, 检查数据。
### 数据格式验证
其次,必须检查输入的数据的正确形式和值。您的代码必须包含适当的逻辑来测试数据的正确性。
#### 例:
```html
<html>
<head>
<title>Form Validation</title>
<script type="text/javascript">
<!--
// Form validation code will come here.
//-->
</script>
</head>
<body>
<form action="/cgi-bin/test.cgi" name="myForm" onsubmit="return(validate());">
<table cellspacing="2" cellpadding="2" border="1">
<tr>
<td align="right">Name</td>
<td><input type="text" name="Name" /></td>
</tr>
<tr>
<td align="right">EMail</td>
<td><input type="text" name="EMail" /></td>
</tr>
<tr>
<td align="right">Zip Code</td>
<td><input type="text" name="Zip" /></td>
</tr>
<tr>
<td align="right">Country</td>
<td>
<select name="Country">
<option value="-1" selected>[choose yours]</option>
<option value="1">USA</option>
<option value="2">UK</option>
<option value="3">INDIA</option>
</select>
</td>
</tr>
<tr>
<td align="right"></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
```
#### 产量
[在这里了解一下](https://liveweave.com/LP9eOP)
### 基本表格验证
首先让我们看看如何进行基本表单验证。在上面的表单中我们调用validate来在onsubmit事件发生时验证数据。该 以下代码显示了此`validate()`函数的实现。
```html
<script type="text/javascript">
// Form validation code will come here.
function validate()
{
if( document.myForm.Name.value == "" )
{
alert( "Please provide your name!" );
document.myForm.Name.focus() ;
return false;
}
if( document.myForm.EMail.value == "" )
{
alert( "Please provide your Email!" );
document.myForm.EMail.focus() ;
return false;
}
if( document.myForm.Zip.value == "" ||
isNaN( document.myForm.Zip.value ) ||
document.myForm.Zip.value.length != 5 )
{
alert( "Please provide a zip in the format #####." );
document.myForm.Zip.focus() ;
return false;
}
if( document.myForm.Country.value == "-1" )
{
alert( "Please provide your country!" );
return false;
}
return( true );
}
</script>
```
#### 产量
[在这里了解一下](https://liveweave.com/pCPTnP)
### 数据格式验证
现在我们将看到如何在将输入的表单数据提交到Web服务器之前验证它们。
以下示例显示如何验证输入的电子邮件地址。电子邮件地址必须至少包含“@”符号和点(。)。此外,'@'必须 不是电子邮件地址的第一个字符,最后一个点必须至少是“@”符号后面的一个字符。
#### 例:
```html
<script type="text/javascript">
function validateEmail()
{
var emailID = document.myForm.EMail.value;
atpos = emailID.indexOf("@");
dotpos = emailID.lastIndexOf(".");
if (atpos < 1 || ( dotpos - atpos < 2 ))
{
alert("Please enter correct email ID")
document.myForm.EMail.focus() ;
return false;
}
return( true );
}
</script>
```
#### 产量
[在这里了解一下](https://liveweave.com/nznVs6)
### HTML5表单约束
`<input>`一些常用HTML5约束是`type`属性(例如`type="password"` `maxlength` `required``disabled` 。少了 常用的约束是采用JavaScript正则表达式的`pattern` attrinute。
### 验证库
验证库的示例包括:
* [Validate.js](http://rickharrison.github.com/validate.js/)
* [验证](http://bassistance.de/jquery-plugins/jquery-plugin-validation/)
* [Valid8](http://unwrongest.com/projects/valid8/)
### 更多信息
* [表格数据验证| MDN](https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation)
* [约束验证| MDN](https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation)
* [Tutorialspoint](https://www.tutorialspoint.com/javascript/javascript_form_validations.htm)

View File

@@ -0,0 +1,67 @@
---
title: Function Composition
localeTitle: 功能组合
---
## 功能构成
函数组合是一个函数对另一个函数的结果的逐点应用。开发人员每天在嵌套功能时以手动方式执行此操作:
```javascript
compose = (fn1, fn2) => value => fn2(fn1(value))
```
但这很难读。使用函数组合有更好的方法。而不是从里到外阅读它们:
```javascript
add2AndSquare = (n) => square(add2(n))
```
我们可以使用更高阶函数以有序的方式链接它们。
```javascript
add2AndSquare = compose( add2, square)
```
compose的一个简单实现是
```javascript
compose = (f1, f2) => value => f2( f1(value) );
```
为了获得更大的灵活性我们可以使用reduceRight函数
```javascript
compose = (...fns) => (initialVal) => fns.reduceRight((val, fn) => fn(val), initialVal);
```
从左到右的阅读构成允许清晰地链接高阶函数。真实世界的例子是添加身份验证,日志记录和上下文属性。这是一种能够在最高级别上实现可重用性的技术。以下是如何使用它的一些示例:
```javascript
// example
const add2 = (n) => n + 2;
const times2 = (n) => n * 2;
const times2add2 = compose(add2, times2);
const add6 = compose(add2, add2, add2);
times2add2(2); // 6
add2tiems2(2); // 8
add6(2); // 8
```
您可能认为这是高级函数式编程它与前端编程无关。但它在单页应用程序中也很有用。例如您可以使用更高阶的组件向React组件添加行为
```javascript
function logProps(InputComponent) {
InputComponent.prototype.componentWillReceiveProps = function(nextProps) {
console.log('Current props: ', this.props);
console.log('Next props: ', nextProps);
};
return InputComponent;
}
// EnhancedComponent will log whenever props are received
const EnhancedComponent = logProps(InputComponent);
```
总之,功能组合使功能的可重用性处于非常高的水平。如果函数结构良好,它使开发人员能够基于现有行为创建新行为。

View File

@@ -0,0 +1,71 @@
---
title: Function Invocation
localeTitle: 函数调用
---
## 函数调用
调用函数时,将执行函数内的代码。通常使用术语“调用函数”而不是“调用函数”。
调用函数时,函数必须在范围内。函数的作用域是声明它的函数,如果它是在顶层声明的整个程序。
```javascript
function myFunction(a, b) {
return a * b;
}
myFunction(10, 2); // Function invocation, will return 20
//optional parameters (es6 only)
//allow to set optional parameters
function myFunction(a, b = 10) {
return a * b;
}
myFunction(1); // Function invocation, will return 10
myFunction(1,5); // Function invocation, will return 5
```
在示例代码中a和b是函数的参数它们保存值10和2它们是函数调用中使用的参数。
### 调用函数作为方法
在JavaScript中您可以将函数定义为对象方法。
以下示例创建一个对象( `myObject` ),其中包含两个属性( `firstName``lastName` )和一个方法( `fullName`
```javascript
var myObject = {
firstName:"John",
lastName: "Doe",
fullName: function () {
return this.firstName + " " + this.lastName;
}
}
myObject.fullName(); // Function invoked as a method, will return "John Doe"
```
### 箭头功能
在最新版本的Javascript中您还可以使用箭头函数缩短语法。 以下演示了两个功能。一个用标准形式写成一个用箭头写成。请记住箭头函数没有自己的thisargumentssuper或new.target。
```javascript
//regular function
function addStuff(args) {
return args + 2;
}
addStuff(2);
//returns 4
//arrow function
var addStuff = (args) => args + 2;
addStuff(2);
//returns 4
```
这个简写版本的箭头函数有一个隐式返回因此您不指定return语句。
### 更多信息:
* 功能文档: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions)

View File

@@ -0,0 +1,61 @@
---
title: Functions List
localeTitle: 功能列表
---
![非官方的JS徽标](//discourse-user-assets.s3.amazonaws.com/original/2X/0/0584980f425bfbbe1e14001557ff4f5bab8f61ec.jpg)
JavaScriptJS是一种具有一流功能的轻量级解释编程语言。最着名的是网页脚本语言许多非浏览器环境也使用它例如[node.js](https://nodejs.org)和[Apache CouchDB](http://couchdb.apache.org/) 。 JS是一种基于原型的多范式动态脚本语言支持面向对象命令式和声明式例如函数式编程样式。
JavaScript在Web的客户端运行可用于设计/编程网页在事件发生时的行为方式。 JavaScript是一种易于学习且功能强大的脚本语言广泛用于控制网页行为。
查看[MDN的JavaScript文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript) ,它们是学习的重要资产。
我们的维基上也有一些很棒的文章:
* [JavaScript的优点和缺点](http://forum.freecodecamp.com/t/advantages-and-disadvantages-of-javascript/14280)
* **JavaScript数据类型**
* [布尔](http://forum.freecodecamp.com/t/javascript-boolean/14311)
* **JavaScript字符串**
* [String.prototype.charAt](http://forum.freecodecamp.com/t/javascript-string-prototype-charat/15932)
* [String.prototype.charCodeAt](http://forum.freecodecamp.com/t/javascript-string-prototype-charcodeat/15933)
* [String.prototype.concat](http://forum.freecodecamp.com/t/javascript-string-prototype-concat/15935)
* [String.prototype.indexOf](https://forum.freecodecamp.org/t/javascript-string-prototype-indexof/15936)
* [String.prototype.lastIndexOf](http://forum.freecodecamp.com/t/string-prototype-lastindexof/15939)
* [String.prototype.match](http://forum.freecodecamp.com/t/javascript-string-prototype-match/15941)
* [String.prototype.replace](http://forum.freecodecamp.com/t/javascript-string-prototype-replace/15942)
* [String.prototype.slice](http://forum.freecodecamp.com/t/javascript-string-prototype-slice/15943)
* [String.prototype.split](http://forum.freecodecamp.com/t/javascript-string-prototype-split/15944)
* [String.prototype.substr](http://forum.freecodecamp.com/t/javascript-string-prototype-substr/15945)
* [String.prototype.substring](http://forum.freecodecamp.com/t/javascript-string-prototype-substring/15947)
* [String.prototype.toLowerCase](http://forum.freecodecamp.com/t/javascript-string-prototype-tolowercase/15948)
* [String.prototype.toUpperCase](http://forum.freecodecamp.com/t/javascript-string-prototype-touppercase/15950)
* **JavaScript数组**
* [Array.isArray](http://forum.freecodecamp.com/t/javascript-array-isarray/14284)
* [Array.prototype.concat](http://forum.freecodecamp.com/t/javascript-array-prototype-concat/14286)
* [Array.prototype.every](http://forum.freecodecamp.com/t/javascript-array-prototype-every/14287)
* [Array.prototype.filter](http://forum.freecodecamp.com/t/javascript-array-prototype-filter/14289)
* [Array.prototype.forEach](http://forum.freecodecamp.com/t/javascript-array-prototype-foreach/14290)
* [Array.prototype.indexOf](http://forum.freecodecamp.com/t/javascript-array-prototype-indexof/14291)
* [Array.prototype.join](http://forum.freecodecamp.com/t/javascript-array-prototype-join/14292)
* [Array.prototype.lastIndexOf](http://forum.freecodecamp.com/t/javascript-array-prototype-lastindexof/14293)
* [Array.prototype.map](http://forum.freecodecamp.com/t/javascript-array-prototype-map/14294)
* [Array.prototype.pop](http://forum.freecodecamp.com/t/javascript-array-prototype-pop/14296)
* [Array.prototype.push](http://forum.freecodecamp.com/t/javascript-array-prototype-push/14298)
* [Array.prototype.reduce](http://forum.freecodecamp.com/t/javascript-array-prototype-reduce/14299)
* [Array.prototype.reverse](http://forum.freecodecamp.com/t/javascript-array-prototype-reverse/14300)
* [Array.prototype.shift](http://forum.freecodecamp.com/t/javascript-array-prototype-shift/14301)
* [Array.prototype.slice](http://forum.freecodecamp.com/t/javascript-array-prototype-slice/14302)
* [Array.prototype.some](http://forum.freecodecamp.com/t/javascript-array-prototype-some/14304)
* [Array.prototype.sort](http://forum.freecodecamp.com/t/javascript-array-prototype-sort/14306)
* [Array.prototype.splice](http://forum.freecodecamp.com/t/javascript-array-prototype-splice/14307)
* [Array.prototype.toString](http://forum.freecodecamp.com/t/javascript-array-prototype-tostring/14308)
* [Array.prototype.unshift](http://forum.freecodecamp.com/t/javascript-array-prototype-unshift/14309)
* **JavaScript循环**
* [循环](http://forum.freecodecamp.com/t/javascript-loops/14681)
* [而Loop](http://forum.freecodecamp.com/t/javascript-while-loop/14668)
* [做循环](http://forum.freecodecamp.com/t/javascript-do-while-loop/14662)
* [对于循环](http://forum.freecodecamp.com/t/javascript-for-loop/14666)
* [对于In Loop](http://forum.freecodecamp.com/t/javascript-for-in-loop/14665)
* [对于循环](http://forum.freecodecamp.com/t/javascript-for-of-loop/14671)
查看我们关于JavaScript的其他文章 [https](https://www.freecodecamp.com/wiki) [//www.freecodecamp.com/wiki](https://www.freecodecamp.com/wiki) 。

View File

@@ -0,0 +1,9 @@
---
title: Get Timestamp
localeTitle: 获取时间戳
---
您可以使用`Date.now()`来获取当前时间戳(以毫秒为单位)。
您可以轻松地将时间戳转换为秒,如下所示: `Math.floor(Date.now() / 1000)`
如果您的浏览器不支持`Date.now()` ,则可以使用`new Date().getTime()`来获取时间戳(以毫秒为单位)。

View File

@@ -0,0 +1,43 @@
---
title: Global Object
localeTitle: 全球对象
---
全局对象是在执行代码之前由JavaScript解释器初始化的对象。在全局范围参见 [Scopes](http://forum.freecodecamp.com/t/scopes-in-javascript/14696) )上声明的所有变量都作为属性存储在全局对象中。
在Node.js环境中全局对象可以通过`global`关键字访问,而在浏览器窗口中,可以通过`window`关键字访问它。在全局范围中使用时, `this`关键字也引用全局对象。请注意,如果启用了`strict mode`则在全局范围内使用`this`将返回`undefined`
例如:
```javascript
// global scope
var foo = "bar";
console.log(global.foo); // bar (in a Node environment)
console.log(window.foo); // bar (in a browser window)
console.log(this.foo); // bar (if strict mode is disabled)
```
函数本地范围与全局范围之间的区别在此非常重要:全局对象仅包含在全局范围内声明的变量,而不包含函数的本地范围。
全局对象还包含`NaN` `undefined``Infinity`属性以及以下函数:
1. `decodeURI()`
2. `decodeURIComponent()`
3. `encodeURI()`
4. `encodeURIComponent()`
5. `escape()`
6. `eval()`
7. `GetObject()`
8. `isFinite()`
9. `isNaN()`
10. `parseFloat()`
11. `parseInt()`
12. `ScriptEngine()`
13. `ScriptEngineBuildVersion()`
14. `ScriptEngineMajorVersion()`
15. `ScriptEngineMinorVersion()`
16. `unescape()`
# 参考
1. MSDN [全局对象Javascript](https://msdn.microsoft.com/en-us/library/52f50e9t)

View File

@@ -0,0 +1,67 @@
---
title: Global Variables
localeTitle: 全局变量
---
全局变量在整个程序的可访问性函数之外声明,而局部变量使用`var`存储在函数中,仅在该函数的[范围内使用](https://developer.mozilla.org/en-US/docs/Glossary/Scope) 。如果在不使用`var`情况下声明变量,即使它在函数内部,它仍将被视为全局变量:
```javascript
var x = 5; //global
function someThing(y) {
var z = x + y;
console.log(z);
}
function someThing(y) {
x = 5; //still global!
var z = x + y;
console.log(z);
}
function someThing(y) {
var x = 5; //local
var z = x + y;
console.log(z);
}
```
全局变量也是当前范围的对象,例如浏览器窗口:
```javascript
var dog = Fluffy;
console.log(dog); //Fluffy;
var dog = Fluffy;
console.log(window.dog); //Fluffy
```
最小化全局变量是最佳实践。由于变量可以在程序中的任何位置访问,因此它们可能导致奇怪的行为。
参考文献:
* [var -Javascript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)
* [您不了解JavaScript范围和闭包](https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures)
附加信息:
* [JavaScript最佳实践避免使用全局](http://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals)
## \* [javascript中的全局var和window.variable有什么区别](https://stackoverflow.com/questions/6349232/whats-the-difference-between-a-global-var-and-a-window-variable-in-javascript)
JavaScript变量的范围是全局变量或本地变量。 全局变量在函数外部声明,其值可在整个程序中访问/更改。
你应该总是使用**var**来声明你的变量在本地生成否则它会安装GLOBALLY
注意全局变量,因为它们存在风险。大多数情况下,您应该使用闭包来声明变量。 例:
```javascript
(function(){
var myVar = true;
})();
```
#### 更多信息:
* [JavaScript最佳实践避免使用全局](http://www.w3.org/wiki/JavaScript_best_practices#Avoid_globals)
* [全局变量很糟糕](http://c2.com/cgi/wiki?GlobalVariablesAreBad)
* [MDN - 全局变量](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)

View File

@@ -0,0 +1,41 @@
---
title: Higher Order Functions
localeTitle: 高阶函数
---
## 高阶函数
高阶函数是在执行时返回函数,将函数作为其一个或多个参数或两者的函数。如果您已经使用了任何`Array`方法(如`map``filter` 或者将回调函数传递给jQuery的`$.get` ,那么您已经使用了高阶函数。
使用`Array.map` ,您提供了一个函数作为其唯一参数,它适用于数组中包含的每个元素。
```javascript
var arr = [ 1, 2, 3 ];
var arrDoubled = arr.map(function(num) {
return num * 2;
});
console.log(arrDoubled); // [ 2, 4, 6 ]
```
高阶函数也可以返回一个函数。例如,您可以创建一个名为`multiplyBy`的函数,它接受一个数字并返回一个函数,该函数将您提供的另一个数字乘以提供的第一个数字。您可以使用此方法创建`multiplyByTwo`函数以传递给`Array.map` 。这将为您提供上面看到的相同结果。
```javascript
function multiplyBy(num1) {
return function(num2) {
return num1 * num2;
}
}
var multiplyByTwo = multiplyBy(2);
var arr = [ 1, 2, 3 ];
var arrDoubled = arr.map(multiplyByTwo);
console.log(arrDoubled); // [ 2, 4, 6 ]
```
有关在上面的示例中`multiplyByTwo`如何保持对`num1`的引用的更多信息,请参阅[Closures](https://guide.freecodecamp.org/javascript/closures)指南。
[有关更多信息Closures](https://eloquentjavascript.net/05_higher_order.html)

View File

@@ -0,0 +1,40 @@
---
title: HTML DOM getElementById Method
localeTitle: HTML DOM getElementById方法
---
`getElementById()`方法返回具有指定值的id属性的元素。它需要一个参数它是所需元素的id的区分大小写的字符串。
此方法是HTML DOM中最常用的方法之一几乎每次您想要操作文档中的元素或从中获取信息时都会使用此方法。这是一个简单的语法示例
**HTML内容**
```html
<div id="demo"></div>
```
**JavaScript内容**
```javascript
document.getElementById("demo"); // Returns the element with id "demo"
```
如果你有多个具有相同`id`值的元素(糟糕的做法!), `getElementById`将返回找到的第一个元素:
```html
<div id="demo">First</div>
<div id="demo">Second</div>
```
```javascript
document.getElementById("demo"); // Returns the element with id "demo" containing 'First'
```
#### 更多信息:
[的document.getElementById](https://developer.mozilla.org/en-US/docs/Web/API/Document/getElementById)
#### 替代方案:
`document.getElementById`一个常用替代方法是使用jQuery选择器您可以在[这里](https://github.com/freeCodeCamp/guides/tree/master/src/pages/jquery)阅读更多内容。

View File

@@ -0,0 +1,60 @@
---
title: HTML Dom Innerhtml Property
localeTitle: HTML Dom Innerhtml属性
---
## HTML Dom Innerhtml属性
`innerHTML` prop返回所选元素中的HTML内容并允许您定义新的HTML内容。
**_获取元素内容_**
```html
<div id="demo">
<p>Demo</p>
</div>
```
```javascript
var element = document.getElementById("demo");
console.log(element.innerHTML) //logs <p>Demo</p>
```
**_设置元素内容_**
```html
<div id="demo"></div>
```
```javascript
var element = document.getElementById("demo");
element.innerHTML = "<div>Demo</div>";
```
HTML现在就像
```html
<div id="demo">
<div>Demo</div>
</div>
```
**_安全考虑_**
设置为`innerHTML`的值应该来自可靠来源因为Javascript会将任何内容放在该元素中并且它将作为纯HTML运行。
例:
设置“ `<script>alert();</script>` ”值将导致Javascript“alert”函数被触发
```javascript
var element = document.getElementById("demo");
element.innerHTML = "<script>alert();</script>";
```
这种类型的攻击称为[Cross Site Scripting简称XSS](https://en.wikipedia.org/wiki/Cross-site_scripting) 。
这是提交XSS攻击的最常见方式之一。如果您想学习更多知识并学会防范它 [请查看此资源](https://xss-game.appspot.com/)

View File

@@ -0,0 +1,38 @@
---
title: HTML DOM querySelector()
localeTitle: HTML DOM querySelector
---
Document方法`querySelector()`返回文档中与指定选择器或选择器组匹配的`first` Element。如果未找到匹配项则返回null。
**HTML内容**
```html
<div id="id-example"></div>
<div class="class-example"></div>
<a>element-example</a>
```
**JavaScript内容**
```javascript
document.querySelector("#id-example"); // Returns the element with id "id-example"
document.querySelector(".class-example"); // Returns the element with class "class-example"
document.querySelector("a"); // Returns the "a" element
```
注意`querySelector()`返回第一个匹配元素返回所有匹配项改为使用querySelectorAll方法。
```html
<div id="example">First</div>
<div id="example">Second</div>
```
```javascript
document.querySelector("#example"); // Returns only the element containing 'First'
```
#### 更多信息:
[MDN - document.querySelector](https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector)

View File

@@ -0,0 +1,44 @@
---
title: HTML Dom
localeTitle: HTML Dom
---
## HTML Dom
使用HTML DOMJavaScript可以访问和更改HTML文档的所有元素。
当网页加载时,浏览器创建页面的**d** **ocumentØbject** **中号**奥德尔。
HTML DOM模型构建为对象树
DOM中的每个元素也称为节点。
```html
<html>
<head>
<title> My title </title>
</head>
<body>
<a href="#">My Link</a>
<h1> My header </h1>
</body>
</html>
```
上述HTML的DOM如下
![DOM树](https://www.w3schools.com/js/pic_htmltree.gif)
使用对象模型JavaScript可以获得创建动态HTML所需的全部功能
* JavaScript可以更改页面中的所有HTML元素
* JavaScript可以更改页面中的所有HTML属性
* JavaScript可以更改页面中的所有CSS样式
* JavaScript可以删除现有的HTML元素和属性
* JavaScript可以添加新的HTML元素和属性
* JavaScript可以对页面中的所有现有HTML事件做出反应
* JavaScript可以在页面中创建新的HTML事件
#### 更多信息:
[W3C - HTML DOM](https://www.w3schools.com/js/js_htmldom.asp)

View File

@@ -0,0 +1,73 @@
---
title: If-Else Statement
localeTitle: If-Else声明
---
## 介绍
`if`指定的条件为`true` `if`语句执行语句。如果条件为`false` ,则可以使用`else`语句执行另一个语句。
**注意:** `else`语句是可选的。
```javascript
if (condition)
/* do something */
else
/* do something else */
```
可以链接多个`if...else`语句来创建`else if`子句。这指定了要测试的新条件,并且可以重复测试多个条件,检查直到执行真实语句。
```javascript
if (condition1)
/* do something */
else if (condition2)
/* do something else */
else if (condition3)
/* do something else */
else
/* final statement */
```
**注意:**如果要在`if` `else``else if`部分中执行多个语句, `if`语句周围需要花括号:
```javascript
if (condition) {
/* do */
/* something */
/* with multiple statements */
} else {
/* do something */
/* else */
}
```
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if…else) | [MSDN链接](https://msdn.microsoft.com/en-us/library/85yyde5c.aspx)
## 例子
**使用** `if...else`
```javascript
// If x=5 z=7 and q=42. If x is not 5 then z=19.
if (x == 5) {
z = 7;
q = 42
else
z = 19;
```
**使用** `else if`
```javascript
if (x < 10)
return "Small number";
else if (x < 50)
return "Medium number";
else if (x < 100)
return "Large number";
else {
flag = 1;
return "Invalid number";
}
```

View File

@@ -0,0 +1,60 @@
---
title: Immediately Invoked Functions Expressions(IIFEs)
localeTitle: 立即调用函数表达式IIFE
---
## 功能说明
使用函数声明创建的函数是Function对象具有Function对象的所有属性方法和行为。 例:
```javascript
function statement(item){
console.log('Function statement example '+ item);
}
```
## 功能表达
函数表达式与函数语句类似,只是可以省略函数名来创建匿名函数。 例:
```javascript
var expression = function (item){
console.log('Function expression example '+ item);
}
```
## 立即调用函数表达式
一旦创建了函数,它就会调用自己不需要显式调用。 在下面的示例变量中iife将存储由函数执行返回的字符串。
```javascript
var iife = function (){
return 'Immediately Invoked Function Expressions(IIFEs) example ';
}();
console.log(iife); // 'Immediately Invoked Function Expressions(IIFEs) example '
```
IIFE之前的声明应始终以a结尾;否则会引发错误。
**不好的例子**
```javascript
var x = 2 //no semicolon, will throw error
(function(y){
return x;
})(x); //Uncaught TypeError: 2 is not a function
```
## 为什么使用立即调用的函数表达式?
```javascript
(function(value){
var greet = 'Hello';
console.log(greet+ ' ' + value);
})('IIFEs');
```
在上面的示例中当javascript引擎执行上面的代码时它会在看到代码时创建全局执行上下文并在内存中为IIFE创建函数对象。 当它到达第`46`行时由于调用了哪个函数动态创建了一个新的执行上下文因此greet变量进入该函数执行上下文而不是全局这使得它是唯一的。 `This ensures that code inside IIFE does not interfere with other code or be interfered by another code` ,因此代码是安全的。
#### 更多信息
[维基百科上立即调用的函数表达式](https://en.wikipedia.org/wiki/Immediately-invoked_function_expression) [JavaScript库中的前导分号有什么作用](https://stackoverflow.com/questions/1873983/what-does-the-leading-semicolon-in-javascript-libraries-do)

View File

@@ -0,0 +1,21 @@
---
title: Immutable Types
localeTitle: 不可变类型
---
> 不可改变意味着不可改变,即你无法改变。
Javascript有很多不可变类型例如`string`基元类型。在您的控制台中试试这个。
```
s = "red";
console.log(s[1]); //→ "e"
s[1] = "x";
console.log(s) //→ "red"
```
`s`没改变! WAT
## 细节
`String.replace`等一些字符串方法返回一个新字符串。
JavaScript有一种复杂的数据类型即Object数据类型它有五种简单的数据类型NumberStringBooleanUndefined和Null。这些简单原始数据类型是不可变的不能更改而对象是可变的可以更改

View File

@@ -0,0 +1,35 @@
---
title: JavaScript
localeTitle: JavaScript的
---
## JavaScript的
JavaScript是地球上使用最广泛的脚本语言。它拥有任何编程语言中最大的图书馆生态系统。
JavaScript是Web的核心语言也是唯一可以在所有主要Web浏览器中运行的编程语言。
值得注意的是JavaScript与Java无关。 [JavaScript世界上最容易被误解的编程语言](http://www.crockford.com/javascript/javascript.html)
JavaScript的官方名称是在标准[ECMA-262](https://www.ecma-international.org/publications/standards/Ecma-262.htm)下定义的ECMAScript
如果您想了解有关JavaScript语言的更多信息以及为何如此广泛使用它请阅读Quincy Larson的文章 - [我应该首先学习哪种编程语言?](https://medium.freecodecamp.org/what-programming-language-should-i-learn-first-%CA%87d%C4%B1%C9%B9%C9%94s%C9%90%CA%8C%C9%90%C9%BE-%C9%B9%C7%9D%CA%8Dsu%C9%90-19a33b0a467d) - 或观看[来自Preethi Kasireddy的](https://www.youtube.com/watch?v=VqiEhZYmvKk)这个[鼓舞人心的视频](https://www.youtube.com/watch?v=VqiEhZYmvKk) 。
## 独立的JavaScript引擎
Mozilla的SpiderMonkey是有史以来第一个用于Mozilla Firefox的JavaScript引擎。 V8谷歌的JavaScript引擎用于谷歌浏览器。
Google Apps脚本一个基于云的/服务器端解释器提供对Google Apps服务和文档的程序化“宏观”控制。
Node.js构建于V8之上这个平台使服务器端应用程序能够用JavaScript编写。
Windows包括JScriptWindows Script Host中的JavaScript变体。
Chakra是Jscript的一个分支由Microsoft开发并用于Edge浏览器。
Mozilla还提供Rhino一种用Java构建的JavaScript实现通常嵌入到Java应用程序中为最终用户提供脚本。
WebKitChromium项目除外实现了JavaScriptCore引擎。
## JavaScript框架
最常用的JavaScript框架是React JSAngular JSCreate JSjQuerynodeJS等。 有关详细信息请点击此[链接](https://javascriptreport.com/the-ultimate-guide-to-javascript-frameworks/)

View File

@@ -0,0 +1,63 @@
---
title: Location Object
localeTitle: 位置对象
---
## 位置对象
“位置”对象提供API应用程序编程接口其允许检索URL设置URL或访问URL的部分。默认情况下它已在Window和Document对象上实现。 注意没有适用于location对象的公共标准但所有主流浏览器都支持它。
### 位置对象属性
|财产|说明| | ---------- | -------------------------------------- ------------------- | |哈希|设置或返回URL |的锚点部分(#) |主持人|设置或返回URL的主机名和端口号 |主机名|设置或返回URL的主机名 | href |设置或返回整个URL | |来源|返回URL的协议主机名和端口号 |路径名|设置或返回URL的路径名 |港口|设置或返回URL的端口号 |协议|设置或返回URL的协议 |搜索|设置或返回URL |的查询字符串部分
### 位置对象方法
|方法|说明| | ----------- | ------------------------------------- --------- | | assign|加载新文档| | reload|重新加载当前文档| | replace|用新的文档替换当前文档
### 例子
可通过以下方式访问位置对象:
```javascript
console.log(window.location);
// > https://guide.freecodecamp.org/javascript/location-object
console.log(document.location);
// > https://guide.freecodecamp.org/javascript/location-object
```
您还可以使用JavaScript以编程方式设置HTML `<a>`元素的Location对象或HTML `<area>`元素。
```javascript
var anchor = document.createElement('a');
anchor.url = "https://guide.freecodecamp.org/javascript/location-object";
```
一旦你有一个带有URL集的对象包括窗口Location API允许你访问URL的部分内容。
```javascript
console.log(anchor.protocol);
// > https:
console.log(anchor.host);
// > guide.freecodecamp.org (includes port number if applicable. Example: guide.freecodecamp.org:8080)
```
您可以访问的“位置”的其他属性包括:
* `anchor.hostname` - _guide.freecodecamp.org_
* `anchor.port` - _8080_
* `anchor.pathname` - _/ javascript / location-object_
* `anchor.origin` - _https://developer.mozilla.org_
如果您的URL包含参数或哈希值您可以像这样访问它们
```javascript
// If your URL is https://guide.freecodecamp.org/javascript?param=location#other-properties
console.log(window.location.search);
// > "?param=location"
console.log(document.location.hash);
// > "#other-properties"
```
#### 更多信息:
[W3C - 位置对象](https://www.w3schools.com/jsref/obj_location.asp) [地点](https://developer.mozilla.org/en-US/docs/Web/API/Location)

View File

@@ -0,0 +1,64 @@
---
title: Location Reload Method
localeTitle: 位置重新加载方法
---
## 位置重新加载方法
JavaScript `Location.reload()`方法提供了在当前URL重新加载页面的方法。
语法如下:
`object.reload(forcedReload);` ,其中`forceReload`是可选参数。
要简单地重新加载页面,您可以输入`window.location`作为对象。
可选参数`force reload`是一个布尔值,如果设置为:
* `True`从服务器重新加载页面(例如,不存储浏览器缓存的数据):
```
window.location.reload(true);
```
* `False`使用浏览器缓存的页面版本重新加载页面。
```
window.location.reload(false);
```
`False`是默认参数,因此如果留空,则`object.reload()`使用`object.reload()`的缓存数据重新加载页面,即与使用`object.reload(false)`方法相同。
要创建浏览器提供的“刷新”选项的效果您可能需要创建HTML按钮并执行以下任一操作
*`Location.reload()`附加到HTML按钮标记如下所示
```
<input type="button" value="Refresh Button" onClick="window.location.reload()">
```
* 使用使用该方法的函数将按钮上的事件分配给按钮,其中按钮看起来类似于
```
<button type="button" onClick="reloadThePage()">Refresh!</button>
```
```
<script>
function reloadThePage(){
window.location.reload();
}
</script>
```
### 例:
```javascript
// Reload the current resources from the server
window.location.reload(true);
// Reload the current resources from the browser's cache
window.location.reload();
```
这将从服务器重新加载当前URL的页面。
#### 更多信息:
* [MDN](https://developer.mozilla.org/docs/Web/API/Location/reload)
* [W3学校](https://www.w3schools.com/jsref/met_loc_reload.asp)

View File

@@ -0,0 +1,96 @@
---
title: Logical Operators
localeTitle: 逻辑运算符
---
# 逻辑运算符
逻辑运算符比较布尔值并返回布尔响应。有两种类型的逻辑运算符 - 逻辑AND和逻辑OR。这些运算符通常写为&&表示AND和||对于OR。
#### 逻辑AND&&
AND运算符比较两个表达式。如果第一个评估为[“truthy”](https://developer.mozilla.org/en-US/docs/Glossary/Truthy) ,则该语句将返回第二个表达式的值。 如果第一个计算为[“falsy”](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) ,则该语句将返回第一个表达式的值。
当只涉及布尔值( `true``false` 如果两个表达式都为真则返回true。如果一个或两个表达式为false则整个语句将返回false。
```js
true && true //returns the second value, true
true && false //returns the second value, false
false && false //returns the first value, false
123 && 'abc' // returns the second value, 'abc'
'abc' && null //returns the second value, null
undefined && 'abc' //returns the first value, undefined
0 && false //returns the first value, 0
```
#### 逻辑OR||
OR运算符比较两个表达式。如果第一个计算为“falsy”则该语句将返回第二个表达式的值。如果第一个评估为“truthy”则该语句将返回第一个表达式的值。
当仅涉及布尔值( `true``false` 如果任一表达式为true则返回true。两个表达式都可以是真的但结果只需要一个表达式。
```js
true || true //returns the first value, true
true || false //returns the first value, true
false || false //returns the second value, false
123 || 'abc' // returns the first value, 123
'abc' || null //returns the first value, 'abc'
undefined || 'abc' //returns the second value, 'abc'
0 || false //returns the second value, false
```
#### 短路评估
&&和||表现为短路运营商。
在逻辑AND的情况下如果第一个操作数返回false则永远不会计算第二个操作数并返回第一个操作数。
如果是逻辑OR如果第一个值返回true则永远不会计算第二个值并返回第一个操作数。
#### 逻辑NOT
NOT运算符不会像AND和OR运算符那样进行任何比较。此外它仅在1个操作数上运行。
一个'' 感叹号标记用于表示NOT运算符。
###### 使用NOT运算符
1. 将表达式转换为布尔值。
2. 返回上一步中获得的布尔值的倒数。
```js
var spam = 'rinki'; //spam may be equal to any non empty string
var booSpam = !spam;
/*returns false
since when a non-empty string when converted to boolean returns true
inverse of which is evaluated to false.
*/
var spam2 = ''; //spam2 here is equal to empty string
var booSpam2 = !spam2;
/*returns true
since when a empty string when converted to boolean returns false
inverse of which is evaluated to true.
*/
```
#### 提示:
两个逻辑运算符都将返回上次计算的表达式的值。例如:
```js
"cat" && "dog" //returns "dog"
"cat" && false //returns false
0 && "cat" //returns 0 (which is a falsy value)
"cat" || "dog" //returns "cat"
"cat" || false //returns "cat"
0 || "cat" //returns "cat"
```
请注意, `&&`返回第一个值, `||`返回第二个值,反之亦然。
#### 更多信息:
* [Javascript真值表](https://guide.freecodecamp.org/javascript/truth-table)
* [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Operators/Logical_Operators)

View File

@@ -0,0 +1,50 @@
---
title: Break Statement
localeTitle: 休息声明
---
## 介绍
**break**语句终止当前循环, `switch``label`语句,并将程序控制转移到终止语句后面的语句。
```
break;
```
如果在带标签的语句中使用**break**语句,则语法如下:
```
break labelName;
```
## 例子
以下函数有一个**break**语句,当**i**为3时终止`while`循环,然后返回值**3 \* x** 。
```
function testBreak(x) {
var i = 0;
while (i < 6) {
if (i == 3) {
break;
}
i += 1;
}
return i * x;
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/C7VM/0)
在以下示例中计数器设置为从1到99计数;但是, **break**语句在14次计数后终止循环。
```
for (var i = 1; i < 100; i++) {
if (i == 15) {
break;
}
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/C7VO/0)
## 其他资源:
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break) | [MSDN链接](https://msdn.microsoft.com/en-us/library/3fhdxafb.aspx)

View File

@@ -0,0 +1,58 @@
---
title: Continue Statement
localeTitle: 继续声明
---
## 介绍
**continue**语句终止当前或标记循环的当前迭代中的语句的执行,并继续执行下一次迭代的循环。
```
continue;
```
如果在带标签的语句中使用**continue**语句,则语法如下:
```
continue labelName;
```
与**break**语句相反, **continue**不会完全终止循环的执行;代替:
*`while`循环中,它会跳回到条件。
*`for`循环中,它跳转到更新表达式。
## 例子
以下示例显示了一个`while`循环,该循环具有一个**continue**语句,该语句在**i的**值为3时执行。因此 **n**取值为1,3,7和12。
```
var i = 0;
var n = 0;
while (i < 5) {
i++;
if (i === 3) {
continue;
}
n += i;
console.log (n);
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/C7hx/0)
在下面的示例中循环从1到9迭代。由于将**continue**语句与表达式`(i < 5)`一起使用,因此跳过了**continue**和`for` body结尾之间的语句。
```
for (var i = 1; i < 10; i++) {
if (i < 5) {
continue;
}
console.log (i);
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/C7hs/0)
## 其他资源
* [MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue)
* [MSDN链接](https://msdn.microsoft.com/en-us/library/8de3fkc8.aspx)

View File

@@ -0,0 +1,38 @@
---
title: Do...While Loop
localeTitle: 做......循环
---
`do...while`循环与[`while`](http://forum.freecodecamp.com/t/javascript-while-loop/14668)循环密切相关。在do while循环中在循环结束时检查条件。
这是`do...while`循环的**语法**
## 句法:
```
do {
*Statement(s);*
} while (*condition*);
```
**statements**在计算条件或布尔表达式之前**至少**执行**一次的**语句,并**在**每次条件计算结果为true时重新执行。
**condition**这里,条件是布尔表达式 。如果布尔表达式的计算结果为true则再次执行该语句。当布尔表达式求值为false时循环结束。
## 例:
```
var i = 0;
do {
i = i + 1;
console.log(i);
} while (i < 5);
Output:
1
2
3
4
5
```
来源: [**做......同时**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do…while)

View File

@@ -0,0 +1,70 @@
---
title: For...In Loop
localeTitle: 对于... In Loop
---
`for...in`语句以任意顺序迭代对象的可枚举属性。对于每个不同的属性,可以执行语句。
```
for (variable in object) {
...
}
```
|必需/可选|参数|说明| | ------------------- | ----------- | ----------------- -------------------------------------------------- --- | |必需|变量|每次迭代都会为变量分配不同的属性名称。 | |可选|对象|迭代其可枚举属性的对象。 |
## 例子
```
// Initialize object.
a = { "a": "Athens", "b": "Belgrade", "c": "Cairo" }
// Iterate over the properties.
var s = ""
for (var key in a) {
s += key + ": " + a[key];
s += "<br />";
}
document.write (s);
// Output:
// a: Athens
// b: Belgrade
// c: Cairo
// Initialize the array.
var arr = new Array("zero", "one", "two");
// Add a few expando properties to the array.
arr["orange"] = "fruit";
arr["carrot"] = "vegetable";
// Iterate over the properties and elements.
var s = "";
for (var key in arr) {
s += key + ": " + arr[key];
s += "<br />";
}
document.write (s);
// Output:
// 0: zero
// 1: one
// 2: two
// orange: fruit
// carrot: vegetable
// Efficient way of getting an object's keys using an expression within the for-in loop's conditions
var myObj = {a: 1, b: 2, c:3}, myKeys = [], i=0;
for (myKeys[i++] in myObj);
document.write(myKeys);
//Output:
// a
// b
// c
```
# 资源:
* [MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for…in)
* [MSDN链接](https://msdn.microsoft.com/library/55wb2d34.aspx)

View File

@@ -0,0 +1,86 @@
---
title: For Loop
localeTitle: 对于循环
---
### 句法
```javascript
for ([initialization]); [condition]; [final-expression]) {
// statement
}
```
javascript `for`语句由三个表达式和一个语句组成:
## 描述
* 初始化 - 在循环上第一次执行之前运行。此表达式通常用于创建计数器。这里创建的变量的范围是循环。一旦循环完成它的执行就会被破坏。
* condition - 在每次迭代执行之前检查的表达式。如果省略则此表达式的计算结果为true。如果计算结果为true则执行循环语句。如果计算结果为false则循环停止。
* final-expression - 每次迭代后运行的表达式。通常用于增加计数器。但它也可以用来递减计数器。
* statement - 要在循环中重复的代码
这三个表达式中的任何一个或语句都可以省略。 For循环通常用于计算一定数量的迭代以重复语句。在条件表达式求值为false之前使用`break`语句退出循环。
## 常见的陷阱
**超过数组的边界**
当多次索引数组时很容易超出数组的边界例如尝试引用3元素数组的第4个元素
```javascript
// This will cause an error.
// The bounds of the array will be exceeded.
var arr = [ 1, 2, 3 ];
for (var i = 0; i <= arr.length; i++) {
console.log(arr[i]);
}
output:
1
2
3
undefined
```
有两种方法可以修复此代码。将条件设置为`i < arr.length``i <= arr.length - 1`
### 例子
迭代0-8的整数
```javascript
for (var i = 0; i < 9; i++) {
console.log(i);
}
output:
0
1
2
3
4
5
6
7
8
```
在条件表达式为false之前中断循环
```javascript
for (var elephant = 1; elephant < 10; elephant+=2) {
if (elephant === 7) {
break;
}
console.info('elephant is ' + elephant);
}
output:
elephant is 1
elephant is 3
elephant is 5
```
### 其他资源
* [MDN - 用于陈述](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)

View File

@@ -0,0 +1,88 @@
---
title: For...Of Loop
localeTitle: 对于...... Of Loop
---
`for...of`语句创建循环遍历可迭代对象包括ArrayMapSetArguments对象等调用自定义迭代挂钩其中包含要为每个不同属性的值执行的语句。
```javascript
for (variable of object) {
statement
}
```
| |说明| | ---------- | ------------------------------------- | |变量|在每次迭代时,将不同属性的值分配给变量。 | |对象|迭代其可枚举属性的对象。 |
## 例子
### 排列
```javascript
let arr = [ "fred", "tom", "bob" ];
for (let i of arr) {
console.log(i);
}
// Output:
// fred
// tom
// bob
```
### 地图
```javascript
var m = new Map();
m.set(1, "black");
m.set(2, "red");
for (var n of m) {
console.log(n);
}
// Output:
// 1,black
// 2,red
```
### 组
```javascript
var s = new Set();
s.add(1);
s.add("red");
for (var n of s) {
console.log(n);
}
// Output:
// 1
// red
```
### 参数对象
```javascript
// your browser must support for..of loop
// and let-scoped variables in for loops
function displayArgumentsObject() {
for (let n of arguments) {
console.log(n);
}
}
displayArgumentsObject(1, 'red');
// Output:
// 1
// red
```
# 其他资源:
* [MDN链接](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Statements/for…of)
* [MSDN链接](https://msdn.microsoft.com/library/dn858238%28v=vs.94%29.aspx?f=255&MSPPError=-2147217396)
* [参数@@ iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments/@@iterator)

View File

@@ -0,0 +1,15 @@
---
title: Loops
localeTitle: 循环
---
循环在JavaScript中用于根据条件执行重复任务。条件通常在分析时返回`true``false` 。循环将继续运行,直到定义的条件返回`false`
循环有三种常见类型:
* [对于](http://forum.freecodecamp.com/t/javascript-for-loop/14666)
* [](http://forum.freecodecamp.com/t/javascript-while-loop/14668)
* [做的](http://forum.freecodecamp.com/t/javascript-for-loop/14662)
您可以键入`js for` `js while``js do while`以获取有关这些内容的更多信息。
> 链接: [MDN **for循环**](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for)

View File

@@ -0,0 +1,34 @@
---
title: Labeled Statement
localeTitle: 标签声明
---
## 标签声明
**Labeled语句**与`break``continue`语句一起使用,用于标识`break``continue`语句适用的语句。
### 句法
\`\`\`\`javascript 标签: 声明
```
### Usage
Without the use of a `labeled` statement the `break` statement can only break out of a loop or a `switch` statement. Using a `labeled` statement allows `break` to jump out of any code block.
#### Example
```
JavaScript的 foo{ console.log“This prints; 打破foo; console.log“这将永远不会打印。”; } console.log“因为执行跳转到这里 / \*输出 这打印: 因为执行跳到这里! \* /
```
When used with a `continue` statement the `labeled` statement allows you to skip a loop iteration, the advantage comes from being able to jump out from an inner loop to an outer one when you have nested loop statements. Without the use of a `labeled` statement you could only jump out of the existing loop iteration to the `next iteration of the same loop.`
#### Example
```
JavaScript的 //没有标记语句当j == i时内部循环跳转到下一次迭代 功能测试() { forvar i = 0; i <3; i ++{ console.log(“i =”+ i; forvar j = 0; j <3; j ++{ ifj === i{ 继续; } console.log(“j =”+ j; } } }
/ \*输出 i = 0注意缺少j = 0 J = 1 J = 2 I = 1 j = 0注意缺少j = 1 J = 2 I = 2 J = 0 j = 1注意缺少j = 2 \* /
//使用带标签的语句我们可以跳转到外部i循环 功能测试 { outerforvar i = 0; i <3; i ++{ console.log(“i =”+ i; forvar j = 0; j <3; j ++{ ifj === i{ 继续外 } console.log(“j =”+ j; } } }
/ \* i = 0j仅在小于i时记录 I = 1 J = 0 I = 2 J = 0 J = 1 \* / \`\`\`
### 更多信息:
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/label)

View File

@@ -0,0 +1,45 @@
---
title: While Loop
localeTitle: 而Loop
---
while循环首先评估条件。如果条件为真则执行语句。如果条件为假则不执行语句。之后while循环结束。
这是while循环的**语法**
## 句法:
```
while (condition)
{
statement(s);
}
```
_statements_只要条件求值为true就执行的语句。
_condition_这里condition是一个布尔表达式在每次循环之前计算。如果此条件的计算结果为true则执行语句。当condition的计算结果为false时继续执行while循环后的语句。
## 例:
```
var i = 1;
while (i < 10)
{
console.log(i);
i++; // i=i+1 same thing
}
Output:
1
2
3
4
5
6
7
8
9
```
_来源 [While Loop - MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while)_

View File

@@ -0,0 +1,29 @@
---
title: Manipulate JavaScript Objects
localeTitle: 操纵JavaScript对象
---
有几种方法可以操纵对象属性,点符号和括号表示法。
使用点表示法向对象添加属性:
```
myObject.myProperty = "myValue";
```
使用括号表示法向对象添加属性:
```javascript
myObject['myProperty'] = "myValue";
```
使用括号表示法,我们可以将变量用作属性名称:
```javascript
var dynamicProperty = "myProperty";
myObject[dynamicProperty] = "myValue";
```
我们也可以删除它们:
```
delete(myObject.myProperty);
```

View File

@@ -0,0 +1,68 @@
---
title: Manipulating Cookies
localeTitle: 操纵Cookies
---
## 操纵Cookies
获取或设置cookie是一项简单的操作可以通过访问浏览器文档对象上的cookie属性来实现。
您可以找到一个令人惊叹且信息丰富的食谱网站,为您的客人烹制外国餐,但它是外语,幸运的是,您可以使用选择下拉列表更改网站上的语言。几天后,您再次访问同一站点为您的母亲制作菜肴,但现在您默认使用您的母语查看该网站。
_该网站会记住您上次访问时选择的语言并以**cookie的**形式存储。现在它通过读取该cookie自动选择您的首选语言。_
`userLanguage:french`
Cookie用于在客户端部分以`name:value`对的形式存储数据。它允许网站在浏览器上存储用户特定信息以供以后使用。存储的信息可以是`sessionID` `userCountry` `visitorLanguage`等。
另一种在客户端存储数据的方法是`localstorage`
### 设置Cookie
可以使用下面的语法设置cookie但强烈建议使用类似于最后提到的库以便让每个人都能更轻松地进行开发。在设置cookie时您也可以设置它的到期时间。如果跳过则在浏览器关闭时会删除cookie。
**请记住特定域设置的cookie只能由该域及其子域读取。**
```javascript
// Using vanilla javascript
document.cookie = 'userLanguage=french; expires=Sun, 2 Dec 2017 23:56:11 UTC; path=/';
//Using JS cookie library
Cookies.set('userLanguage', 'french', { expires: 7, path: '/' });
```
_Cookie将在7天后到期_
### 获取Cookie
```javascript
// Using vanilla javascript
console.log(document.cookie)
// => "_ga=GA1.2.1266762736.1473341790; userLanguage=french"
// Using JS cookie library
Cookies.get('userLanguage');
// => "french"
```
### 删除Cookie
为了删除cookie将过期日期设置为过去的某些内容。
```javascript
// Using vanilla javascript
document.cookie = 'userLanguage; expires=Thu, 01 Jan 1970 00:00:01 GMT; path=/';
//Using JS cookie library
Cookies.remove('userLanguage');
```
_如果您发现自己在项目中玩了很多cookie请使用像这样的[JS Cookie](https://github.com/js-cookie/js-cookie)这样的库节省大量时间。_
#### 更多信息:
* [Cookie解释道](https://www.quirksmode.org/js/cookies.html)
* [MDN Cookie指南](https://developer.mozilla.org/en-US/docs/Web/API/document/cookie)
* [Udacity Cookie视频](https://www.youtube.com/watch?v=xdH9zsW1CK0)
* [HTTP cookie](https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies)

View File

@@ -0,0 +1,12 @@
---
title: Multiply Two Numbers with JavaScript
localeTitle: 使用JavaScript将两个数字相乘
---
JavaScript使用`*`符号进行乘法运算。
```
var product = 8 * 10;
```
此产品后,'product'的值为'80'。
在进行计算时,可以使用括号来确定哪些数字应该相乘的优先级。

View File

@@ -0,0 +1,27 @@
---
title: Naming Convention for JavaScript
localeTitle: JavaScript的命名约定
---
在这里,您将了解广泛使用的不同代码案例。
## 骆驼香烟盒
在编程中变量名称的camelCase格式如下所示
```
var camelCase = "lower-case first word, capitalize each subsequent word";
```
## PascalCase
PascalCase或CamelCase是camelCase的变体。它与camelCase的不同之处在于大写每个单词 _包括_第一个单词
```
var PascalCase = "upper-case every word";
```
## snake\_case
另一个名为snake\_case的流行案例以这种方式用下划线分隔每个单词
```
var snake_case = "lower-case everything, but separate words with underscores";
```

View File

@@ -0,0 +1,79 @@
---
title: Numbers
localeTitle: 数字
---
## 数字
JavaScript `number`的实现基于`IEEE 754`标准,通常称为“浮点”。
[IEEE 754维基百科链接](https://en.wikipedia.org/wiki/IEEE_754) [IEEE 754双精度浮点可视化](http://bartaz.github.io/ieee754-visualization/)
数字文字通常表示为`base-10`十进制文字。
```javascript
var foo = 47;
var bar = 47.9;
```
十进制值的前导部分(如果为`0` )是可选的:
```javascript
var same = 0.47;
var stillSame = .47;
```
同样,后面的十进制值的尾部(小数) `.` ,如果为`0` ,则是可选的:
```javascript
var a = 47.0;
var b = 47.;
```
默认情况下,大多数数字将输出为`base-10`小数,并删除尾随小数`0` 。所以:
```javascript
var foo = 47.300;
var bar = 47.0;
foo; // 47.3
bar; // 47
```
非常大或非常小的`numbers`可写为:
```javascript
var foo = 47e8; // 4700000000
var baz = 47e-8; // 00.00000047
```
`toExponential`方法可用于将`number`转换为`exponential notation`
```javascript
var foo = 47e8;
foo; // 4700000000
foo.toExponential() //"47e8"
```
Numbers可以访问`Number.prototype`中内置的方法。
例如: `toFixed()`方法格式化一个具有小数点右侧特定位数的数字。
```javascript
var foo = 47.69;
foo.toFixed(0); // "48"
foo.toFixed(1); // "47.7"
foo.toFixed(2); // "47.69"
```
> 在浏览器中键入`Number.prototype`并自己查看其他可用方法。
#### 更多信息:
1. [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type)
2. [JavaScript编号](https://www.w3schools.com/js/js_numbers.asp)
#### 参考
1. Kyle Simpson的[类型和语法](https://github.com/getify/You-Dont-Know-JS/tree/master/types%20%26%20grammar) 。
2. [ECMAScript语言规范4.3.20](https://www.ecma-international.org/ecma-262/5.1/#sec-4.3.20)
3. [ECMAScript语言规范15.7数字对象](https://www.ecma-international.org/ecma-262/5.1/#sec-15.7)

View File

@@ -0,0 +1,151 @@
---
title: Functional
localeTitle: 实用
---
```javascript
var fun = function(a, b) {
var funInstance = {};
funInstance.a = a;
funInstance.b = b;
funInstance.method1 = function() {
// method code here
}
funInstance.method2 = function() {
// method code here
}
funInstance.method3 = function() {
// method code here
}
return funInstance;
}
var myFun = fun(1, 2);
myFun.method1();
```
## 我怎么认出来的?
功能对象实例化创建一个带有函数的类实例,就像其他选项一样。不同之处在于所有相关方法也在构造函数中定义。
## 我为什么要用它?
由于为对象的每个实例创建了一组新方法并且可能占用大量内存因此当您知道不打算使用大量实例时功能实例化是有益的。新的和经验丰富的JavaScript编码器也能轻松理解您的代码因为实例化完全是自包含的并且很容易看到方法和对象实例之间的关系。
## 有什么缺点?
功能实例化的缺点是,如果要对代码进行任何更改(例如添加更多方法),则在进行这些更改之前创建的对象的任何实例都不会更新。最终可能会有两个包含不同方法信息的实例。
* * *
## 标题:功能共享
```javascript
var fun = function(a, b) {
var funInstance = {};
funInstance.a = a;
funInstance.b = b;
extend(funInstance, funMethods);
return funInstance;
}
var extend = function(to, from) {
for (var key in from) {
to[key] = from[key];
}
}
var funMethods = {};
funMethods.method1 = function() {
// method code here
}
funMethods.method2 = function() {
// method code here
}
funMethods.method3 = function() {
// method code here
}
var myFun = fun(1, 2);
myFun.method1();
```
## 我怎么认出来的?
Functional和Functional-Shared之间的主要区别在于在Functional-Shared中我们共享我们的方法。我们有一个单独的对象来保存我们的所有方法而不是在我们的Instantiation函数中声明方法。为了使用这些方法我们将它们扩展到正在创建的对象的每个实例中。
## 我为什么要用它?
Functional-Shared允许我们使用对方法的引用而不是为我们对象的每个实例声明和存储我们的方法从而节省了空间。
## 有什么缺点?
缺点是,由于方法是通过指向方法对象的指针引用的,如果我们以任何方式更新方法对象,那么在更改之前创建的对象实例将不会更新。最终可能会有两个对象实例引用两个不同版本的方法。
* * *
## 标题:原型
```javascript
var fun = function(a, b) {
var funInstance = Object.create(funMethods);
funInstance.a = a;
funInstance.b = b;
return funInstance;
}
var funMethods = {};
funMethods.method1 = function() {
// method code here
}
funMethods.method2 = function() {
// method code here
}
funMethods.method3 = function() {
// method code here
}
var myFun = fun(1, 2);
myFun.method1();
```
## 我怎么认出来的?
Prototypal类似于Functional-Shared因为它们都使用单独的方法对象来保存将在我们创建的对象的实例之间共享的所有方法。不同之处在于我们可以使用原型链。我们可以使用Object.createprototype创建对象以便将方法附加到我们的对象实例。持有我们共享方法的对象被认为是原型。
## 我为什么要用它?
如果在创建对象实例后对原型进行更改,则将更新该实例。你不会得到两个具有不同方法的相同原型的实例。
## 有什么缺点?
使用此方法的缺点是需要额外的步骤和额外的代码。我们不仅要像以前一样创建和返回我们的对象,还要装饰它。
* * *
## 标题:伪古典
```javascript
var Fun = function(a, b) {
// this = Object.create(Fun.prototype);
this.a = a;
this.b = b;
// return this;
}
Fun.prototype.method1 = function() {
// method code here
}
Fun.prototype.method2 = function() {
// method code here
}
Fun.prototype.method3 = function() {
// method code here
}
var myFun = new Fun(1, 2);
myFun.method1();
```
## 我怎么认出来的?
伪古典实例化到目前为止包含的代码量最少。 new关键字不是创建新对象并返回它而是为我们做到这一点。在引擎盖下当您使用new关键字实例化对象时使用this = Object.createObject.prototype创建一个新对象其中这指的是以new关键字命名的原型。当我们定义方法时我们使用prototype关键字。
## 我为什么要用它?
Pseudoclassical被认为是最快的实例化模式如果您要创建数万个实例这将非常有用。它也是最优化的因为它利用了Javascript功能。
## 有什么缺点?
Pseudoclassical Instantiation的缺点是它需要更多关于JavaScript正在做什么的知识特别是使用this关键字。这使得这种类型的对象实例化更难以理解特别是如果其他人正在阅读您的代码

View File

@@ -0,0 +1,72 @@
---
title: Object Instantiation
localeTitle: 对象实例化
---
## 对象实例化
在Javascript和大多数其他语言中对象包含一系列属性这些属性是键值对。当您需要构造对象时可以使用多个选项。
### 初始化对象变量
您可以创建具有预定义属性的对象,如下所示:
```javascript
let myObject = {
name: "Dave",
age: 33
}
```
### 创建一个空对象
这会在myObject变量中创建一个空对象
```javascript
let myObject = new Object();
```
当您希望向对象添加属性时,只需使用点表示法或括号表示法以及您选择的属性名称:
```javascript
myObject.name = "Johnny Mnemonic"
myObject["age"] = 55
```
### 使用构造函数
您可以定义可用于创建对象的构造函数:
```javascript
function Kitten(name, cute, color) {
this.name = name,
this.cute = cute,
this.color = color
}
```
您可以通过调用构造函数来定义包含此对象实例化的变量:
```javascript
let myKitten = new Kitten("Nibbles", true, "white")
```
### 的Object.create
Object.create方法首先在ECMAScript 5.1中定义)允许您创建对象。它允许您为新对象选择原型对象,而无需事先定义构造函数。
```javascript
// Our pre-defined object
let kitten = {
name: "Fluff",
cute: true,
color: "gray"
}
// Create a new object using Object.create(). kitten is used as the prototype
let newKitten = Object.create(kitten)
console.log(newKitten.name) // Will output "Fluff"
```
#### 更多信息
[关于使用对象的MDN文章](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects)

View File

@@ -0,0 +1,67 @@
---
title: Onclick Event
localeTitle: Onclick活动
---
## Onclick活动
JavaScript中的`onclick`事件允许您作为程序员在单击元素时执行函数。
### 例
```javascript
<button onclick="myFunction()">Click me</button>
<script>
function myFunction() {
alert('Button was clicked!');
}
</script>
```
在上面的简单示例中,当用户单击按钮时,他们将在浏览器中看到显示`Button was clicked!`的警报`Button was clicked!`
### 动态添加`onclick`
`onclick`事件也可以使用以下示例中的以下代码以编程方式添加到任何元素:
```javascript
<p id="foo">click on this element.</p>
<script>
var p = document.getElementById("foo"); // Find the paragraph element in the page
p.onclick = showAlert; // Add onclick function to element
function showAlert(event) {
alert("onclick Event triggered!");
}
</script>
```
### 注意
重要的是要注意使用onclick我们只能添加一个监听器功能。如果要添加更多内容只需使用addEventListener这是添加事件侦听器的首选方法。
在上面的示例中,当用户单击`html``paragraph`元素时,他们将看到显示`onclick Event triggered`的警报。
### 防止默认操作
但是,如果我们重视`onclick`以链接HTML是`a`标签),我们可能想阻止默认动作发生:
```javascript
<a href="https://guide.freecodecamp.org" onclick="myAlert()">Guides</a>
<script>
function myAlert(event) {
event.preventDefault();
alert("Link was clicked but page was not open");
}
</script>
```
在上面的例子中,我们防止了默认行为`a`使用元件(开口链路) `event.preventDefault()`提供了内部`onclick`回调函数。
[MDN](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onclick)
#### 其他资源
[jQuery .on事件处理程序附件](https://api.jquery.com/on/)

View File

@@ -0,0 +1,31 @@
---
title: Onload Event
localeTitle: Onload事件
---
## Onload事件
`onload`事件用于在加载页面后立即执行JavaScript函数。
### 例:
```javascript
<body onload="myFunction()">
<script>
function myFunction() {
alert('Page finished loading');
}
</script>
```
在上面的示例中,只要加载了网页,就会调用`myFunction`函数,向用户显示`Page finished loading`警报。
`onload`事件最常用于`<body>`元素中以执行脚本。如果它附加到`<body>` 则一旦网页完全加载了所有内容图像脚本文件CSS文件等脚本就会运行。
#### 更多信息:
[MDN](https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onload)
#### 其他资源
[jQuery .on事件处理程序附件](https://api.jquery.com/on/) [Stack Overflowwindow.onload与document.onload](https://stackoverflow.com/questions/588040/window-onload-vs-document-onload)

View File

@@ -0,0 +1,105 @@
---
title: Output
localeTitle: 产量
---
## 产量
您可以通过控制台输出数据的最常用方法有4种。这些将在您的开发过程的大部分时间使用。
#### `console.log`
它是输出数据的最常用和最常用的方式。通常的做法是在语句之间插入其中的几个来理解数据的流动和处理方式。此外您可以在devtools中使用`debugger`或断点来执行相同操作,而不会污染您的代码。
```javascript
var numbers = [ 1, 2, 3, 4, 5, 6, 7];
numbers.forEach(function(number){
console.log(number + ' is divisible by 2', number%2 == 0);
});
```
#### `console.warn`
正如您所猜测的那样,它用于显示警告,并且它的典型黄色区别于错误红色和`console.log`
```javascript
function isAdult(age){
if(Number(age) < 18){
console.warn('You are not an adult');
return false;
}
return true;
}
```
#### `console.error`
您可以猜测,这是在抛出异常或在代码中出错时使用的。为您提供红色错误消息以快速引起注意。
#### `console.table`
假设你有一个json对象中的项目或电影列表并且你想以表格格式检查出来那么`console.table`是你最好的选择。它会自动检测数据中的行和列标题。
_尝试在控制台中运行以下代码_
```javascript
var data = {
"colors": [
{
"color": "black",
"category": "hue",
"type": "primary",
"rgba": [255,255,255,1],
"hex": "#000"
},
{
"color": "white",
"category": "value",
"rgba": [0,0,0,1],
"hex": "#FFF"
},
{
"color": "red",
"category": "hue",
"type": "primary",
"rgba": [255,0,0,1],
"hex": "#FF0"
},
{
"color": "blue",
"category": "hue",
"type": "primary",
"rgba": [0,0,255,1],
"hex": "#00F"
},
{
"color": "yellow",
"category": "hue",
"type": "primary",
"rgba": [255,255,0,1],
"hex": "#FF0"
},
{
"color": "green",
"category": "hue",
"type": "secondary",
"rgba": [0,255,0,1],
"hex": "#0F0"
},
]
}
console.table(data.colors);
```
此外,您可以控制和过滤您希望在控制台中看到的输出类型。
1. 所有
2. 详细
3. 警告
4. 错误
#### 更多信息:
* [Google完整引用控制台对象](https://developers.google.com/web/tools/chrome-devtools/console/console-reference)
* [控制台MDN](https://developer.mozilla.org/en-US/docs/Web/API/Console)

View File

@@ -0,0 +1,70 @@
---
title: Popup Boxes
localeTitle: 弹出框
---
## 弹出框
弹出框(或对话框)是用于通知或警告用户或从用户获得输入的模态窗口。
弹出框阻止用户访问程序的其他方面,直到弹出窗口关闭,因此不应过度使用它们。
JavaScript中使用了三种不同的弹出方法 [window.alert](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert) [window.confirm](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)和[window.prompt](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt) 。
### 警报
[警报方法](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert)显示不需要用户输入响应的消息。调用此函数后,将出现一个警告对话框,其中包含指定的(可选)消息。在警报消失之前,用户需要确认消息。
### 例:
`window.alert("Welcome to our website");`
![MDN警报示例](https://mdn.mozillademos.org/files/130/AlertHelloWorld.png)
### 确认
[confirm方法](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)类似于`window.alert()` 但在弹出窗口中也显示一个取消按钮。按钮返回布尔值true表示OKfalse表示取消。
### 例:
```javascript
var result = window.confirm('Are you sure?');
if (result === true) {
window.alert('Okay, if you're sure.');
} else {
window.alert('You seem uncertain.');
}
```
![MDN确认示例](https://mdn.mozillademos.org/files/7163/firefoxcomfirmdialog_zpsf00ec381.png)
### 提示
[提示方法](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt)通常用于从用户获取文本输入。此函数可以使用两个参数,这两个参数都是可选的:要显示给用户的消息和要在文本字段中显示的默认值。
### 例:
`var age = prompt('How old are you?', '100');`
![MDN提示示例](https://mdn.mozillademos.org/files/11303/prompt.png)
### 其他设计选项:
如果您对默认的JavaScript弹出窗口不满意可以在各种UI库中替换。例如SweetAlert为标准JavaScript模式提供了一个很好的替代品。您可以通过CDN内容分发网络将其包含在HTML中并开始使用。
```HTML
<script src="https://unpkg.com/sweetalert/dist/sweetalert.min.js"></script>
```
语法如下: `swal(title, subtitle, messageType)`
```javascript
swal("Oops!", "Something went wrong on the page!", "error");
```
上面的代码将生成以下弹出窗口: ![SweetAlert示例](https://ludu-assets.s3.amazonaws.com/lesson-content/rWqOoQXgDrSVSMrAKiZ9) SweetAlert绝不是标准模态的唯一替代品但它干净且易于实现。
#### 更多信息:
* [MDN window.alert](https://developer.mozilla.org/en-US/docs/Web/API/Window/alert)
* [MDN window.confirm](https://developer.mozilla.org/en-US/docs/Web/API/Window/confirm)
* [MDN window.prompt](https://developer.mozilla.org/en-US/docs/Web/API/Window/prompt)

View File

@@ -0,0 +1,175 @@
---
title: Promises
localeTitle: 承诺
---
## 承诺
JavaScript是单线程的这意味着两个脚本不能同时运行;他们必须一个接一个地跑。 Promise是一个对象表示异步操作的最终完成或失败及其结果值。
```javascript
var promise = new Promise(function(resolve, reject) {
// do thing, then…
if (/* everything worked */) {
resolve("See, it worked!");
}
else {
reject(Error("It broke"));
}
});
```
## 承诺存在于其中一种状态中
* 待定:初始状态,既未履行也未拒绝。
* 实现:操作成功完成。
* 拒绝:操作失败。
Promise对象用作创建promise时未必知道的值的代理。它允许您将处理程序与异步操作的最终成功值或失败原因相关联。这允许异步方法返回类似于同步方法的值异步方法返回一个承诺在将来的某个时刻提供值而不是立即返回最终值。
## 使用'然后'(承诺链接)
要进行多次异步调用并依次同步它们可以使用promise chaining。这允许在后面的后续回调中使用第一个promise中的值。
```javascript
Promise.resolve('some')
.then(function(string) { // <-- This will happen after the above Promise resolves (returning the value 'some')
return new Promise(function(resolve, reject) {
setTimeout(function() {
string += 'thing';
resolve(string);
}, 1);
});
})
.then(function(string) { // <-- This will happen after the above .then's new Promise resolves
console.log(string); // <-- Logs 'something' to the console
});
```
## 承诺API
Promise类中有4个静态方法
* Promise.resolve
* Promise.reject
* Promise.all
* Promise.race
## 承诺可以链接在一起
编写Promise来解决特定问题时可以将它们链接在一起形成逻辑。
```javascript
var add = function(x, y) {
return new Promise((resolve,reject) => {
var sum = x + y;
if (sum) {
resolve(sum);
}
else {
reject(Error("Could not add the two values!"));
}
});
};
var subtract = function(x, y) {
return new Promise((resolve, reject) => {
var sum = x - y;
if (sum) {
resolve(sum);
}
else {
reject(Error("Could not subtract the two values!"));
}
});
};
// Starting promise chain
add(2,2)
.then((added) => {
// added = 4
return subtract(added, 3);
})
.then((subtracted) => {
// subtracted = 1
return add(subtracted, 5);
})
.then((added) => {
// added = 6
return added * 2;
})
.then((result) => {
// result = 12
console.log("My result is ", result);
})
.catch((err) => {
// If any part of the chain is rejected, print the error message.
console.log(err);
});
```
这对于遵循_功能编程_范例很有用。通过创造 用于操纵数据的函数可以将它们链接在一起以组装最终数据 结果。如果在函数链中的任何一点一个值被_拒绝_链 将跳到最近的`catch()`处理程序。
有关函数编程的更多信息: [函数编程](https://en.wikipedia.org/wiki/Functional_programming)
## 函数发生器
在最近的版本中JavaScript引入了更多本机处理Promises的方法。一种这样的方法是函数发生器。函数发生器是“可暂停”的函数。与Promises一起使用时生成器可以使用起来更容易阅读并显示为“同步”。
```javascript
const myFirstGenerator = function* () {
const one = yield 1;
const two = yield 2;
const three = yield 3;
return 'Finished!';
}
const gen = myFirstGenerator();
```
这是我们的第一个生成器,您可以通过`function*`语法看到它。我们声明的`gen`变量不会运行`myFirstGenerator` ,而是“此生成器可以使用”。
```javascript
console.log(gen.next());
// Returns { value: 1, done: false }
```
当我们运行`gen.next()` ,它将取消暂停生成器并继续运行。由于这是我们第一次调用`gen.next()` ,它将运行`yield 1`并暂停,直到我们再次调用`gen.next()` 。当调用`yield 1` ,它将返回给我们产生的`value`以及生成器是否`done`
```javascript
console.log(gen.next());
// Returns { value: 2, done: false }
console.log(gen.next());
// Returns { value: 3, done: false }
console.log(gen.next());
// Returns { value: 'Finished!', done: true }
console.log(gen.next());
// Will throw an error
```
当我们继续调用`gen.next()` ,它将继续进行下一次`yield`并且每次都暂停。一旦没有剩余`yield` ,它将继续运行发电机的其余部分,在这种情况下只返回`'Finished!'` 。如果再次调用`gen.next()` ,它将在生成器完成时抛出错误。
现在,假设这个例子中的每个`yield`都是`Promise` ,代码本身看起来非常同步。
### Promise.alliterable对于对不同源的多个请求非常有用
Promise.alliterable方法返回单个Promise当可迭代参数中的所有promise都已解析或者iterable参数不包含promise时它将解析。它拒绝了第一个承诺拒绝的原因。
```javascript
var promise1 = Promise.resolve(catSource);
var promise2 = Promise.resolve(dogSource);
var promise3 = Promise.resolve(cowSource);
Promise.all([promise1, promise2, promise3]).then(function(values) {
console.log(values);
});
// expected output: Array ["catData", "dogData", "cowData"]
```
### 更多信息
有关承诺的更多信息: [承诺](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)

View File

@@ -0,0 +1,106 @@
---
title: Prototypes
localeTitle: 原型
---
## 原型
JavaScript是一种基于原型的语言因此理解原型对象是JavaScript从业者需要知道的最重要的概念之一。本文将通过各种示例简要概述Prototype对象。在阅读本文之前您需要对[JavaScript](/src/pages/javascript/this-reference/index.md)中的[`this`引用](/src/pages/javascript/this-reference/index.md)有一个基本的了解。
### 原型对象
为清楚起见,我们来看一下以下示例:
```javascript
function Point2D(x, y) {
this.x = x;
this.y = y;
}
```
当声明`Point2D`函数时,将为它创建一个名为`prototype`的默认属性请注意在JavaScript中函数也是一个对象`prototype`属性是一个包含`constructor`属性的对象,其值为`Point2D`函数: `Point2D.prototype.constructor = Point2D` 。当您使用`new`关键字调用`Point2D`时, _新创建的对象将继承_ `Point2D.prototype` _所有属性_ 。要检查这一点,您可以将名为`move`的方法添加到`Point2D.prototype` ,如下所示:
```javascript
Point2D.prototype.move = function(dx, dy) {
this.x += dx;
this.y += dy;
}
var p1 = new Point2D(1, 2);
p1.move(3, 4);
console.log(p1.x); // 4
console.log(p1.y); // 6
```
`Point2D.prototype`被称为**原型对象**或`p1`对象的**原型** ,以及用`new Point2D(...)`语法创建的任何其他对象。您可以根据需要向`Point2D.prototype`对象添加更多属性。常见的模式是`Point2D.prototype`声明方法,其他属性将在构造函数中声明。
JavaScript中的内置对象以类似的方式构造。例如
* 使用`new Object()``{}`语法创建的对象的原型是`Object.prototype`
* 使用`new Array()``[]`语法创建的数组的原型是`Array.prototype`
* 等等其他内置对象,如`Date``RegExp`
`Object.prototype`由所有对象继承,并且没有原型(其原型为`null` )。
### 原型链
原型链机制很简单:当您访问对象`obj`上的属性`p`JavaScript引擎将在`obj`对象中搜索此属性。如果引擎无法搜索,它会继续搜索`obj`对象的原型,依此类推,直到达到`Object.prototype` 。如果在搜索完成后,没有找到任何结果,则结果将是`undefined` 。 例如:
```javascript
var obj1 = {
a: 1,
b: 2
};
var obj2 = Object.create(obj1);
obj2.a = 2;
console.log(obj2.a); // 2
console.log(obj2.b); // 2
console.log(obj2.c); // undefined
```
在上面的代码片段中,语句`var obj2 = Object.create(obj1)`将使用原型`obj1`对象创建`obj2`对象。换句话说,默认情况下, `obj1`成为`obj2`的原型而不是`Object.prototype` 。如您所见, `b`不是`obj2`的属性,您仍然可以通过原型链访问它。但是,对于`c`属性,您将获得`undefined`值,因为它无法在`obj1``Object.prototype`找到。
### 类
在ES2016中我们现在可以使用`Class`关键字以及上面提到的方法来操作`prototype` 。 JavaScript `Class`吸引了来自OOP背景的开发人员但它基本上与上面做了同样的事情。
```javascript
class Rectangle {
constructor(height, width) {
this.height = height
this.width = width
}
get area() {
return this.calcArea()
}
calcArea() {
return this.height * this.width
}
}
const square = new Rectangle(10, 10)
console.log(square.area) // 100
```
这基本上与以下相同:
```javascript
function Rectangle(height, width) {
this.height = height
this.width = width
}
Rectangle.prototype.calcArea = function calcArea() {
return this.height * this.width
}
```
类中的`getter``setter`方法将Object属性绑定到将在查找该属性时调用的函数。这只是语法糖有助于更容易_查找_或_设置_属性。
**进一步阅读:**
* [MDN对象原型](https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Object_prototypes)

View File

@@ -0,0 +1,110 @@
---
title: Random Method
localeTitle: 随机方法
---
## 随机方法
JavaScript `Math.random()`方法是一种出色的内置方法,用于生成随机数。执行`Math.random()` 它返回一个随机数该数字可以介于0和1之间。包括0排除1。
### 生成0到1之间的随机浮点数
`Math.random()`方法将返回一个大于或等于0且小于但绝不等于1的浮点十进制数。换句话说 `0 <= x < 1` 。例如:
```JavaScript
console.log(Math.random());
// 0.7069207248635578
console.log(Math.random());
// 0.765046694794209
console.log(Math.random());
// 0.14069121642698246
```
(当然,每次返回的数字都会有所不同。这将在以下所有示例中假设 - 每次传递都会产生不同的结果。)
要获得较大范围之间的随机数,请将`Math.random()`的结果乘以数字。
### 生成0到指定最大值之间的随机浮点数
通常你不需要0到1之间的随机数 - 你需要更大的数字甚至整数。
例如如果您想要一个0到10之间的随机浮点数您可以使用
```JavaScript
var x = Math.random()*10;
console.log(x);
// 4.133793901445541
```
### 生成范围内的随机浮点数
如果您需要一个介于两个特定数字之间的随机浮点数,您可以执行以下操作:
```JavaScript
var min = 83.1;
var max = 193.36;
var x = Math.random()*(max - min)+min;
console.log(x);
// 126.94014012699063
```
### 生成0到最大值之间的随机整数
通常你需要整数。要做到这一点,你必须使用`Math`对象中的一些其他方法, `Math.floor()` (向下`Math.floor()`入到最接近的整数)和`Math.ceil()` (向上`Math.ceil()`入到最接近的整数)。
例如如果您需要从10个元素的数组中随机选择则需要一个介于0和9之间的随机数请记住数组是零索引的
```JavaScript
var x = Math.floor(Math.random()*10);
console.log(x);
// 7
```
(请记住, `Math.random()`永远不会返回1因此`Math.random()*10`将永远不会返回10.这意味着在向下舍入后结果将始终为9或更小。
### 生成1到最大值之间的随机整数
如果您需要一个最小数为1的随机数例如在一月中选择一个随机日您可以使用`Math.ceil()`方法。
```JavaScript
var x = Math.ceil(Math.random()*31);
console.log(x);
// 23
```
另一种方法是使用前一个函数(使用`Math.floor()` 并向其中添加1
```JavaScript
var x = Math.floor(Math.random()*31)+1;
console.log(x);
// 17
```
### 生成范围内的随机整数
最后,偶尔需要两个特定整数之间的随机整数。例如,如果您尝试选择抽奖券并且您知道最低和最大数字的数字:
```JavaScript
var min = 1718;
var max = 3429;
var x = Math.floor(Math.random()*(max-min+1)+min);
console.log(x);
//2509
```
### Math.random的随机性如何
可以指出, `Math.random()`返回的数字是伪随机数,因为没有计算机可以生成真正的随机数,它表现出所有尺度和所有大小的数据集的随机性。但是, `Math.random()`生成的伪随机数通常足以满足您编写的几乎任何程序的需要。非真实随机性仅在天文数字大集合中或在需要非常精确的小数时才变得明显。
### 更多信息:
* 文档: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/random)

View File

@@ -0,0 +1,96 @@
---
title: Regular Expressions Reference
localeTitle: 正则表达式参考
---
## 正则表达式参考
在JavaScript中正则表达式是用于匹配字符串的所需部分的简写。在尝试操作或验证代码中使用的字符串时这些都很有用。
### 句法
正则表达式由两部分组成 - `pattern``flags` (可选)。模式在两个正斜杠之间写入,后跟可选标志: `var exp = /pattern/flags`
#### 模式
使用字母数字AZaz0-9字符可以直接匹配。然而正则表达式的真正力量来自于字符类。
比方说例如您希望所有地方都有一个数字从0到9的字符串。您可以使用`/\d/`的特殊字符类,而不是显式调用`/[0-9]/` `/\d/` 。反斜杠会转义`d`字符(因此与字母`d`不匹配),而是使用`\d`的特殊匹配功能。
同样的原则适用于非数字字符,空格和其他广泛匹配组。使用某些修饰符(例如`+`字符),正则表达式会变得更加复杂。
此量词允许您将模式中的前一个字符匹配一次或多次。 `/s+/`将匹配`desert`中的`s`和两者`s` `dessert`
还有更多的修饰符可以让你的模式匹配你可能需要的任何东西。请参阅下面的“更多信息”部分,以查看在正则表达式中使用的所有可能的字符选项。
#### 旗
您可以使用5个标志将特定规则应用于您正在编写的整个正则表达式。他们是
`g` - 全球比赛;这允许您匹配表达式的所有实例,而不是在第一次出现后停止。
`i` - 忽略大小写匹配(不言自明)
`m` - 多线匹配;这会将您的模式应用于每一行作为新的;如果您要搜索以特定模式开头的行,则对所有行都这样做,而不是仅对第一行进行
`u` - Unicode匹配;这表示将您的模式读取为Unicode而不是纯文本
`y` - 粘性匹配;这与您的模式匹配`RegExp.lastIndex`属性中找到的索引开始
### 创建正则表达式
正则表达式是一种对象。它可以构建 使用RegExp构造函数或通过将其括起来写为文字值 正斜杠(/)字符中的模式。
```
var re1 = new RegExp (" abc ") ;
var re2 = / abc /;
```
这两个正则表达式对象都表示相同的模式a 一个字符后跟ab后跟一个c。
### RegExp对象
`RegExp`是一个构造函数,它根据您创建的正则表达式模式创建对象。除了上面描述的文字符号,您还可以使用构造函数格式来创建正则表达式: `new RegExp(pattern[, flags])`
### 测试比赛
```
console . log (/ abc /. test (" abcde ") );
// → true
console . log (/ abc /. test (" abxde ") );
// → false
```
### 匹配一组字符
```
console . log (/[0123456789]/. test (" in 1992") );
// → true
console . log (/[0 -9]/. test (" in 1992") );
// → true
```
### 选择模式
```
var animalCount = /\ b \ d + ( pig | cow | chicken )s ?\ b /;
console . log ( animalCount . test ("15 pigs ") );
// → true
console . log ( animalCount . test ("15 pigchickens ") );
// → false
```
#### 方法
您很可能在`String`方法中使用正则表达式,例如`String.replace()` ,但是有一些属于`RegExp`对象的方法。
例如, `RegExp.test()`将返回一个布尔值,表示正则表达式模式与相关字符串之间是否存在匹配。 `RegExp.toString()`会将表达式对象转换为字符串,这在代码上运行测试时非常方便。
第一个参数也可以是正则表达式在这种情况下替换正则表达式的第一个匹配。当ag选项for global添加到正则表达式时字符串中的所有匹配项将被替换而不仅仅是第一个。
```
console . log (" Borobudur ". replace (/[ ou ]/ , "a ") );
// → Barobudur
console . log (" Borobudur ". replace (/[ ou ]/g , "a ") );
// → Barabadar
```
### 更多信息:
* [在这里,您可以阅读](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp)所有模式匹配字符,对象属性,查看一些示例等。
* [这是一个很棒的网站](https://regex101.com/) ,可以让您实时测试正则表达式模式,保存您的收藏夹并探索其他人制作的模式。

View File

@@ -0,0 +1,37 @@
---
title: Rest Parameters
localeTitle: 休息参数
---
## 休息参数
在ES6中其余的参数语法`...`允许您将无限数量的参数收集到数组中。
尽管它们看起来相同,但它与扩展运算符相反,后者从迭代中获取每个项目并将它们分散到各自的值中。
### 句法
```js
function myFunc(...args) {
console.log(args);
}
myFunc( 1, 2, 3, 4, 5); // [1,2,3,4,5]
```
你可以在它前面加上函数的最后一个参数与`...`当你想要做的初始paramters的东西然后把所有剩下的参数不同。
```js
function convertCurrency(rate, fee, ...amounts) {
return amounts.map(amount => (amount * rate) + fee);
}
convertCurrency(0.89, 2.5, 100, 250, 75, 150, 300); // [ 91.5, 225, 69.25, 136, 269.5 ]
```
`...`允许您将其余参数(如果有的话)收集到数组中。
### rest参数和arguments对象之间的区别
`arguments`是一个类似于数组的对象,在函数内部可用,包含传递给这些函数的参数。它被称为“类似数组”,因为它没有所有数组的内置方法,例如`.forEach()``.map()`
其余参数是一个数组,包含所有数组方法。

View File

@@ -0,0 +1,86 @@
---
title: Return Statement
localeTitle: 退货声明
---
## 介绍
在函数中调用**return**语句时,将停止执行此函数。如果指定,则将给定值返回给函数调用者。如果省略表达式,则返回`undefined`
```js
return expression;
```
函数可以返回:
* 原始值(字符串,数字,布尔值等)
* 对象类型(数组,对象,函数等)
切勿在不使用括号的情况下在新行上返回某些内容。这是一个JavaScript怪癖结果将是未定义的。尝试在多行返回时使用括号。
```javascript
function foo() {
return
1;
}
function boo() {
return (
1
);
}
foo(); --> undefined
boo(); --> 1
```
## 例子
以下函数返回其参数**x**的平方,其中**x**是数字。
```js
function square(x) {
return x * x;
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/C7VT/0)
以下函数返回其参数**arg1**和**arg2**的乘积。
```js
function myfunction(arg1, arg2){
var r;
r = arg1 * arg2;
return(r);
}
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/C7VU/0)
当函数`return` sa值时可以使用assigment运算符 `=` )将该值赋给变量。在下面的示例中,函数返回参数的平方。当函数结算或结束时,其值为`return`值。然后将该值分配给变量`squared2`
```javascript
function square(x) {
return x * x;
}
let squared2 = square(2); // 4
```
如果没有显式的return语句意味着该函数缺少`return`关键字,则该函数会自动返回`undefined` 。在以下示例中, `square`函数缺少`return`关键字。将调用函数的结果赋给变量时,变量的值为`undefined`
```javascript
function square(x) {
let y = x * x;
}
let squared2 = square(2); // undefined
```
![:rocket:](//forum.freecodecamp.com/images/emoji/emoji_one/rocket.png?v=2 ":火箭:") [运行代码](https://repl.it/M8BE)
#### 更多信息:
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return)
[MSDN链接](https://msdn.microsoft.com/en-us/library/22a685h9.aspx)

View File

@@ -0,0 +1,131 @@
---
title: Scopes
localeTitle: 领域
---
如果你已经用JavaScript编程了一段时间那么毫无疑问你会遇到一个称为`scope`的概念。什么是`scope` ?你为什么要花时间学习它?
在程序员说话中, `scope`是**当前执行的上下文** 。困惑?我们来看看以下代码:
```
var foo = 'Hi, I am foo!';
var baz = function () {
var bar = 'Hi, I am bar too!';
console.log(foo);
}
baz(); // Hi, I am foo!
console.log(bar); // ReferenceError...
```
这是一个简单的例子但它很好地说明了所谓的_词法范围_ 。 JavaScript和几乎所有其他编程语言都有一个_词法范围_ 。还有另一种称为_动态范围的范围_ ,但我们不会讨论它。
现在术语_词汇范围_看起来很奇特但正如你将看到它原则上非常简单。在词法范围中有两种范围 _全局范围_和_局部范围_ 。
在程序中键入第一行代码之前会为您创建一个_全局范围_ 。这包含您在程序中声明的**所有函数之外的所有变量** 。
在上面的示例中,变量`foo`位于程序的全局范围内,而变量`bar`在函数内声明,因此**位于该函数的本地范围内** 。
让我们逐行分解示例。虽然你可能会在这一点上感到困惑,但我保证你读完这篇文章时会有更好的理解。
在第1行我们声明变量`foo` 。这里没什么太花哨的。让我们称之为`foo`的左手大小LHS引用因为我们正在为`foo`分配一个值,它位于`equal`的左侧。
在第3行我们声明一个函数并将其赋值给变量`baz` 。这是对`baz`另一个LHS参考。我们正在为它赋值请记住函数也是值。然后在第8行调用此函数。这是一个RHS或者是对`baz`的右侧引用。我们正在检索`baz`的值,在这种情况下是一个函数然后调用它。如果我们将其值分配给另一个变量,例如`foo = baz` ,则另一个对`baz` RHS引用。这将是对`foo`的LHS参考和对`baz`的RHS参考。
LHS和RHS参考文献可能听起来令人困惑但它们对于讨论范围很重要。可以这样想LHS参考是为变量赋值而RHS参考则是检索变量的值。它们只是一种更简单更方便的方式来表示“检索价值”和“分配价值”。
现在让我们分析一下函数本身内部发生了什么。
当编译器在函数内编译代码时,它进入函数的**本地范围** 。
在第4行声明变量`bar` 。这是一个LHS参考`bar` 。在下一行,我们在`console.log()`有一个对`foo`的RHS引用。请记住我们正在检索`foo`的值,然后将其作为参数传递给方法`console.log()`
当我们有一个对`foo`的RHS引用时编译器会查找变量`foo`的声明。编译器在函数本身或**函数的本地范围中**找不到它,因此它**上升到一个级别:到全局范围** 。
此时您可能认为范围与变量有关。那是对的。范围可以被视为变量的容器。在本地范围内创建的所有变量只能在该本地范围内访问。但是,所有本地范围都可以访问全局范围。 (我知道你现在可能更加困惑,但只要跟我说几句话)。
因此编译器进入全局范围以查找变量`foo`的LHS引用。它在第1行找到一个所以它从LHS引用中检索值这是一个字符串 `'Hi, I am foo!'` 。此字符串将发送到`console.log()`方法,并输出到控制台。
编译器已经完成了函数内部的代码执行所以我们回到第9行。在第9行我们有一个变量`bar`的RHS参考。
现在, `bar``baz`的本地范围内被声明但是在全球范围内有一个RHS参考`bar` 。由于全局范围内没有`bar` LHS引用因此编译器无法找到`bar`的值并抛出ReferenceError。
但是您可能会问如果函数可以在变量外部查看或者本地范围可以查看全局范围以查找LHS引用为什么全局范围不能窥探到本地范围那就是词汇范围的工作原理
```
... // global scope
var baz = function() {
... // baz's scope
}
... /// global scope
```
这是与上面相同的代码,说明了范围。这形成了一种符合全球范围的层次结构:
`baz -> global`
因此,如果在`baz`范围内存在变量的RHS参考则可以通过全局范围内该变量的LHS参考来实现。但**事实**恰恰相反。
如果我们在`baz`内部有另一个功能怎么办?
```
... // global scope
var baz = function() {
... // baz's scope
var bar = function() {
... // bar's scope.
}
}
... /// global scope
```
在这种情况下,层次结构或**范围链**将如下所示:
`bar -> baz -> global`
内部的任何RHS引用`bar`的本地范围可以通过在全球范围内或LHS引用被fullfilled `baz`适适用范围“但在RHS参考`baz`的范围不能用在LHS参考fullfilled `bar`适适用范围”。
**您只能遍历范围链,而不是向上遍历。**
关于JavaScript范围您还应该了解其他两个重要事项。
1. 范围由函数声明,而不是由块声明。
2. 函数可以是前向引用的,变量不能。
观察(每个注释描述其写入的行的范围):
\`\`\` // outer在此范围内因为函数可以是前向引用的
```
function outer() {
// only inner() is in scope here
// because only functions are forward-referenced
var a = 1;
//now 'a' and inner() are in scope
function inner() {
var b = 2
if (a == 1) {
var c = 3;
}
// 'c' is still in scope because JavaScript doesn't care
// about the end of the 'if' block, only function inner()
}
// now b and c are out of scope
// a and inner() are still in scope
}
// here, only outer() is in scope
```
\`\`\`
# 参考
1. Kyle Simpson的[范围和闭包](https://github.com/getify/You-Dont-Know-JS/tree/master/scope%20%26%20closures) 。它详细介绍了作用域机制的工作原理并对JavaScript编译器的工作原理进行了表面描述因此如果您对此感兴趣请务必阅读它在GitHub上是免费的可以从O'Reilly购买。
2. John Resig和Bear Bibeault [的JavaScript Ninja](https://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/1617292850/ref=pd_lpo_sbs_14_img_0?_encoding=UTF8&psc=1&refRID=YMC2TB2C0DFHTQ3V62CA)的[秘密](https://www.amazon.com/Secrets-JavaScript-Ninja-John-Resig/dp/1617292850/ref=pd_lpo_sbs_14_img_0?_encoding=UTF8&psc=1&refRID=YMC2TB2C0DFHTQ3V62CA) 。这是一个更深入理解JavaScript的好指南。

View File

@@ -0,0 +1,29 @@
---
title: Semicolons
localeTitle: 分号
---
Javascript中不需要分号。这是因为Javascript有一个名为“自动分号插入”的功能或简称ASI。 ASI会为您的Javascript添加分号。默认情况下它始终处于活动状态它是语言的一部分无法禁用。
ASI有一套规则用于确定应该在哪里插入分号。如果已经存在分号则不会改变任何内容。有关ASI如何工作的更多信息请参阅[此StackOverflow答案](http://stackoverflow.com/a/2846298/3467946) 。
只有一种情况是ASI失败当一行以一个开括号开始时`(` 。为了避免这种情况导致错误,当一行以一个开括号开头时,你可以在一行开头的分号处加一个分号:
```js
;(function() {
console.log('Hi!')
})
```
请注意,只有在不使用分号时才需要这样做。
一致的编码风格使代码更具可读性。决定你是否会使用分号,并在任何地方都这样做。
## 您可能遇到的错误
当Javascript首次制作时它旨在帮助初学者进入编程。当他们第一次开始编程时没有人想在他们的代码中搜索dang分号。因此实施了分号的选择如上所述它们在技术上存在。
例如: `javasctipt function foo(x) { return function(y) { return x + y; } } let z = foo(10); z(10)// TypeError z is not a function // Because of Automatic Semicolon Insertion, our inner function does not exist.` Javasctipt将实现预期的分号。
### 其他资源
[关于分号的JavaScript领导人的公开信](http://blog.izs.me/post/2353458699/an-open-letter-to-javascript-leaders-regarding)

View File

@@ -0,0 +1,51 @@
---
title: Creating Singleton In JavaScript
localeTitle: 在JavaScript中创建Singleton
---
## 在Javascript指南中创建Singleton
这篇文章是关于在NativeJavascript中创建单身人士。这个概念对于维护干净的代码很有用。
如果你想维护你的代码,或者某些数据在整个应用程序中应保持相同,这就是你完成它的方法。
**先验知识** 这只是为了帮助您更轻松地理解概念,否则您始终可以复制粘贴代码并相应地进行更改。
* 基本的Javascript语法
* Javascript函数
* Javascript中的IIFE
### 让我们开始吧
让我们创建具有IIFE功能的对象该功能将立即执行以使我们能够使用Singleton。
```
var singletonFn = (function(){ //Created IIFE Function
var dataCounter = 0;
return { //Any code inside this return stuff will be accessible directly using objectname.
getDataCounter: function(){
return dataCounter;
},
setDataCounter: function(val){
dataCounter = val;
},
fishNames: ["SimpleFish"] //Can create variables, Arrays, etc.
}
})();
```
现在执行或使用你的单身人士。在将此文件保存到js文件并加载后在浏览器中。
```
console.log(singletonFn.getDataCounter()); //0 as bydefault it will be 0.
singletonFn.setDataCounter(20);
console.log(singletonFn.getDataCounter()); //20 as we assigned.
console.log(fishNames); //will Print array with "SimpleFish".
```
现在有了这些知识,您可以定义常量,枚举或需要在此处编写的项目中使用多个的任何内容。或类似配置的东西。
希望,这将帮助您编写更好的代码。快乐编码:)

View File

@@ -0,0 +1,147 @@
---
title: Spread syntax
localeTitle: 传播语法
---
## 传播语法
Spread语法允许在可能需要零个或多个参数用于函数调用或元素用于数组文字的位置扩展可迭代的数组表达式或字符串或者在预期为零的位置展开对象表达式。
### 句法
对于函数调用:
```
myFunction(...iterableObj);
```
对于数组文字或字符串:
```
[...iterableObj, '4', 'five', 6];
```
### 例子
#### 传播函数调用
#### 替换申请
在要使用数组元素作为函数参数的情况下,通常使用`Function.prototype.apply`
```
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction.apply(null, args);
```
使用扩展语法,上面可以写成:
```
function myFunction(x, y, z) { }
var args = [0, 1, 2];
myFunction(...args);
```
参数列表中的任何参数都可以使用扩展语法,并且可以多次使用。
```
function myFunction(v, w, x, y, z) { }
var args = [0, 1];
myFunction(-1, ...args, 2, ...[3]);
```
### 申请新的
当使用`new`调用构造函数时,不可能**直接**使用数组并`apply` `apply`执行`[[Call]]`而不是`[[Construct]]` )。但是,由于扩展语法,可以很容易地使用数组:
```
var dateFields = [1970, 0, 1]; // 1 Jan 1970
var d = new Date(...dateFields);
```
要使用带有参数数组的new而不使用扩展语法您必须通过部分应用程序**间接**执行此操作:
```
function applyAndNew(constructor, args) {
function partial () {
return constructor.apply(this, args);
};
if (typeof constructor.prototype === "object") {
partial.prototype = Object.create(constructor.prototype);
}
return partial;
}
function myConstructor () {
console.log("arguments.length: " + arguments.length);
console.log(arguments);
this.prop1="val1";
this.prop2="val2";
};
var myArguments = ["hi", "how", "are", "you", "mr", null];
var myConstructorWithArguments = applyAndNew(myConstructor, myArguments);
console.log(new myConstructorWithArguments);
// (internal log of myConstructor): arguments.length: 6
// (internal log of myConstructor): ["hi", "how", "are", "you", "mr", null]
// (log of "new myConstructorWithArguments"): {prop1: "val1", prop2: "val2"}
```
### 传播数组文字
#### 一个更强大的数组文字
如果没有扩展语法要使用现有数组作为其中一部分创建新数组则数组文字语法不再足够必须使用pushspliceconcat等组合使用命令式代码。使用扩展语法变得更加简洁
```
var parts = ['shoulders', 'knees'];
var lyrics = ['head', ...parts, 'and', 'toes'];
// ["head", "shoulders", "knees", "and", "toes"]
```
就像扩展参数列表一样, `...`可以在数组文字中的任何地方使用,并且可以多次使用。
### 复制一个数组
```
var arr = [1, 2, 3];
var arr2 = [...arr]; // like arr.slice()
arr2.push(4);
// arr2 becomes [1, 2, 3, 4]
// arr remains unaffected
```
> **注意** 在复制数组时Spread语法有效地深入一级。因此它可能不适合复制多维数组如下例所示与Object.assign和spread语法相同
```
var a = [[1], [2], [3]];
var b = [...a];
b.shift().shift(); // 1
// Now array a is affected as well: [[], [2], [3]]
```
### 连接数组的更好方法
`Array.concat`通常用于将数组连接到现有数组的末尾。没有扩展语法,这可以完成:
```
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
// Append all items from arr2 onto arr1
arr1 = arr1.concat(arr2);
```
使用扩展语法,这将成为:
```
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1 = [...arr1, ...arr2];
```
`Array.unshift`通常用于在现有数组的开头插入值数组。没有扩展语法,这可以完成:
```
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
// Prepend all items from arr2 onto arr1
Array.prototype.unshift.apply(arr1, arr2) // arr1 is now [3, 4, 5, 0, 1, 2]
```
使用扩展语法,这将成为:
```
var arr1 = [0, 1, 2];
var arr2 = [3, 4, 5];
arr1 = [...arr2, ...arr1]; // arr1 is now [3, 4, 5, 0, 1, 2]
```

View File

@@ -0,0 +1,91 @@
---
title: Array Destructuring
localeTitle: 数组解构
---
# 数组解构
解构是从存储在数组中的数据中提取多个值的便捷方式。它可以在接收数据的位置使用(例如,分配的左侧)。 `ECMAScript 6`引入了此功能。
如何提取值通过模式指定(请参阅示例)。
### 基本变量赋值
```
var names = ['neel', 'meet', 'darshan'];
var [nameOne, nameTwo, nameThree] = names;
console.log(nameOne); // "neel"
console.log(nameTwo); // "meet"
console.log(nameThree); // "darshan"
```
### 与声明分开的作业
变量可以通过与变量声明分开的解构来赋值。
```
var a, b;
[a, b] = [1, 2];
console.log(a); // 1
console.log(b); // 2
```
### 默认值
如果`undefined`从数组中解压缩的值,则可以为变量分配默认值。
```
var a, b;
[a=5, b=7] = [1];
console.log(a); // 1
console.log(b); // 7
```
### 解析从函数返回的数组
始终可以从函数返回数组。解构可以使数组返回值更简洁。
在此示例中, `getNames()`返回值`['neel', 'meet']`作为其输出,可以使用解构在单行中进行解析。
```
function getNames() {
return ['neel', 'meet'];
}
var neel, meet;
[nameOne, nameTwo] = getNames();
console.log(nameOne); // neel
console.log(nameTwo); // meet
```
### 忽略一些返回的值
您可以忽略您不感兴趣的返回值:
```
function getNames() {
return ['neel', 'meet', 'darshan'];
}
var [nameOne, , nameThree] = getNames();
console.log(nameOne); // neel
console.log(nameThree); // darshan
```
您还可以忽略所有返回的值:
```
[,,] = getNames();
```
### 将数组的其余部分分配给变量
解构数组时可以使用rest模式解压缩并将其余部分分配给变量
```
var [a, ...b] = [1, 2, 3];
console.log(a); // 1
console.log(b); // [2, 3]
```
请注意如果在左侧使用带有rest元素的尾随逗号则将抛出`SyntaxError`
```
var [a, ...b,] = [1, 2, 3];
// SyntaxError: rest element may not have a trailing comma
```
另请参见: **数组解构** | [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Array_destructuring)

View File

@@ -0,0 +1,19 @@
---
title: Array from
localeTitle: 数组来自
---
## 数组来自
'Array.from'方法从类似数组或可迭代的对象创建一个新的Array实例。
### 句法:
“”” Array.fromarrayLike \[mapFn \[thisArg\]\] “””
### 例:
“”” Array.from '富'; // \[“f”“o”“o”\] “””
#### 更多信息:
[MDN文档](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/from)

View File

@@ -0,0 +1,38 @@
---
title: Array isArray
localeTitle: Array isArray
---
如果对象是数组,则`Array.isArray()`方法返回`true`否则返回`false`
## 句法
```
Array.isArray(obj)
```
### 参数
**obj**要检查的对象。
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) | [MSDN链接](https://msdn.microsoft.com/en-us/LIBRary/ff848265%28v=vs.94%29.aspx)
## 例子
```
// all following calls return true
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
// Little known fact: Array.prototype itself is an array:
Array.isArray(Array.prototype);
// all following calls return false
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });
```

View File

@@ -0,0 +1,26 @@
---
title: Array Length
localeTitle: 数组长度
---
## 数组长度
`length`是JavaScript中数组的一个属性它返回或设置给定数组中的元素数。
可以像这样返回数组的`length`属性。
```js
let desserts = ["Cake", "Pie", "Brownies"];
console.log(desserts.length); // 3
```
赋值运算符与`length`属性一起可用于设置数组中的元素数量,如此。
```js
let cars = ["Saab", "BMW", "Volvo"];
cars.length = 2;
console.log(cars.length); // 2
```
#### 更多信息:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global\_Objects/Array/length

View File

@@ -0,0 +1,27 @@
---
title: Array of
localeTitle: 数组
---
## 数组
无论参数的数量或类型如何Array.of方法都会创建一个具有可变数量参数的新Array实例。
句法:
```javascript
Array.of(element0[, element1[, ...[, elementN]]])
```
## 例
```javascript
Array.of(7); // [7] - creates an array with a single element
Array.of(1, 2, 3); // [1, 2, 3]
Array(7); // [ , , , , , , ] - creates an empty array with a length property of 7
Array(1, 2, 3); // [1, 2, 3]
```
#### 更多信息:
有关更多信息,请访问[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of)

View File

@@ -0,0 +1,45 @@
---
title: Array.prototype.concat
localeTitle: Array.prototype.concat
---
## Array.prototype.concat
'concat'方法返回一个新数组,该数组由您调用它的数组元素组成,后跟参数传递顺序的元素。
您可以将多个参数传递给'concat'方法。参数可以是数组,也可以是布尔值,字符串和数字等数据类型。
### 句法
```javascript
const newArray = array.concat(value1, value2, value3...);
```
### 例子
#### 连接两个数组
```javascript
var cold = ['Blue', 'Green', 'Purple'];
var warm = ['Red', 'Orange', 'Yellow'];
var result = cold.concat(warm);
console.log(result);
// results in ['Blue', 'Green', 'Purple', 'Red', 'Orange', 'Yellow'];
```
#### 将值连接到数组
```javascript
const odd = [1, 3, 5, 7, 9];
const even = [0, 2, 4, 6, 8];
const oddAndEvenAndTen = odd.concat(even, 10);
console.log(oddAndEvenAndTen);
// results in [1, 3, 5, 7, 9, 0, 2, 4, 6, 8, 10];
```
#### 更多信息:
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat)

View File

@@ -0,0 +1,11 @@
---
title: Array.prototype.copyWithin
localeTitle: Array.prototype.copyWithin
---
## Array.prototype.copyWithin
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/array/array-prototype-copywithin/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@@ -0,0 +1,11 @@
---
title: Array.prototype.entries
localeTitle: Array.prototype.entries
---
## Array.prototype.entries
这是一个存根。 [帮助我们的社区扩展它](https://github.com/freecodecamp/guides/tree/master/src/pages/javascript/standard-objects/array/array-prototype-entries/index.md) 。
[这种快速风格指南有助于确保您的拉取请求被接受](https://github.com/freecodecamp/guides/blob/master/README.md) 。
#### 更多信息:

View File

@@ -0,0 +1,74 @@
---
title: Array.prototype.every
localeTitle: Array.prototype.every
---
`every()`方法测试数组中的所有元素是否都通过了由提供的函数实现的测试。
**句法**
```javascript
arr.every(callback[, thisArg])
```
## 参数
* **callback**函数测试每个元素,取三个参数:
* **currentValue** (必填)
当前元素在数组中处理。
* **索引** (可选)
数组中正在处理的当前元素的索引。
* **数组** (可选)
每个阵列都被调用了。
* **thisArg**可选。执行回调时要使用的值。
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every) | [MSDN链接](https://msdn.microsoft.com/en-us/LIBRary/ff679981%28v=vs.94%29.aspx)
## 描述
`every`方法按升序索引顺序为每个数组元素调用`every` `callback`函数,直到`callback`函数返回false。如果找到导致`callback`返回false的元素则every方法立即返回`false` 。否则every方法返回`true`
不会为缺少的数组元素调用回调函数。
除了数组对象之外每个方法都可以被具有length属性且具有数字索引属性名称的任何对象使用。 `every`都不会改变调用它的数组。
## 例子
```javascript
function isBigEnough(element, index, array) {
return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough); // false
[12, 54, 18, 130, 44].every(isBigEnough); // true
// Define the callback function.
function CheckIfEven(value, index, ar) {
document.write(value + " ");
if (value % 2 == 0)
return true;
else
return false;
}
// Create an array.
var numbers = [2, 4, 5, 6, 8];
// Check whether the callback function returns true for all of the
// array values.
if (numbers.every(CheckIfEven))
document.write("All are even.");
else
document.write("Some are not even.");
// Output:
// 2 4 5 Some are not even.
```

View File

@@ -0,0 +1,26 @@
---
title: Array.prototype.fill
localeTitle: Array.prototype.fill
---
## Array.prototype.fill
fill方法使用静态值填充数组中的所有元素。
句法:
\`\`\`\`javascript arr.fill arr.fill开始 arr.fill开始结束
```
The fill method takes up to three arguments value, start and end. The start and end arguments are optional with default values of 0 and the length of the this object.
The fill method is a mutable method, it will change this object itself, and return it, not just return a copy of it.
## Examples
```
JavaScript的 \[1,2,3\] .fill4; // \[4,4,4\] \[1,2,3\] .fill4,1; // \[1,4,4\]
var fruits = \[“Grape”“Pear”“Apple”“Strawberry”\]; fruits.fill“西瓜”2,4; //香蕉,梨,西瓜,西瓜 \`\`\`
#### 更多信息:
有关更多信息,请访问[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill)

View File

@@ -0,0 +1,78 @@
---
title: Array.prototype.filter
localeTitle: Array.prototype.filter
---
## Array.prototype.filter
filter方法将数组作为输入。它接受数组中的每个元素并对它应用条件语句。如果此条件返回true则元素被“推送”到输出数组。
一旦输入数组中的每个元素都被“过滤”它就会输出一个包含返回true的每个元素的新数组。
在下面的示例中有一个数组其中包含多个对象。通常要遍历此数组您可以使用for循环。
在这种情况下我们希望得到所有成绩大于或等于90的学生。
```javascript
var students = [
{ name: 'Quincy', grade: 96 },
{ name: 'Jason', grade: 84 },
{ name: 'Alexis', grade: 100 },
{ name: 'Sam', grade: 65 },
{ name: 'Katie', grade: 90 }
];
//Define an array to push student objects to.
var studentsGrades = []
for (var i = 0; i < students.length; i++) {
//Check if grade is greater than 90
if (students[i].grade >= 90) {
//Add a student to the studentsGrades array.
studentsGrades.push(students[i])
}
}
return studentsGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
```
这个for循环有效但它非常冗长。对于需要迭代的许多数组一遍又一遍地编写循环也会变得很繁琐。
这是过滤器的一个很好的用例!
以下是使用过滤器的相同示例:
```javascript
var students = [
{ name: 'Quincy', grade: 96 },
{ name: 'Jason', grade: 84 },
{ name: 'Alexis', grade: 100 },
{ name: 'Sam', grade: 65 },
{ name: 'Katie', grade: 90 }
];
var studentGrades = students.filter(function (student) {
//This tests if student.grade is greater than or equal to 90. It returns the "student" object if this conditional is met.
return student.grade >= 90;
});
return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
```
编写过滤器的方法要快得多读取时更清晰同时仍然可以完成同样的事情。使用ES6语法我们甚至可以使用过滤器复制6行for循环
```javascript
var students = [
{ name: 'Quincy', grade: 96 },
{ name: 'Jason', grade: 84 },
{ name: 'Alexis', grade: 100 },
{ name: 'Sam', grade: 65 },
{ name: 'Katie', grade: 90 }
];
var studentGrades = students.filter(student => student.grade >= 90);
return studentGrades; // [ { name: 'Quincy', grade: 96 }, { name: 'Alexis', grade: 100 }, { name: 'Katie', grade: 90 } ]
```
过滤器非常有用是一个很好的选择for循环来过滤数组对条件语句。
#### 更多信息:
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)

View File

@@ -0,0 +1,71 @@
---
title: Array.prototype.find
localeTitle: Array.prototype.find
---
## 信息
`find()`方法返回数组中第一个满足提供的测试函数的元素的值。否则返回undefined。 `find()`方法不会改变调用它的数组。
句法:
```
arr.find(callback[, thisArg])
```
##### 参数
* `callback`
* 函数对数组中的每个值执行,取三个参数:
* `element`
* 当前元素在数组中处理。
* `index`
* 数组中正在处理的当前元素的索引。
* `array`
* 数组查找被调用。
* `thisArg` (可选)
* 执行回调时要用作此对象的对象。
##### 返回值
元素通过测试时数组中的值;否则,未定义。
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)
## 例子
此示例将在数组中找到相应的项并从中返回对象。
```javascript
let items = [
{name: 'books', quantity: 2},
{name: 'movies', quantity: 1},
{name: 'games', quantity: 5}
];
function findMovies(item) {
return item.name === 'movies';
}
console.log(items.find(findMovies));
// Output
// { name: 'movies', quantity: 1 }
```
以下示例显示了回调函数的每个可选参数的输出。这将返回`undefined`因为没有任何项将从回调函数返回true。
```javascript
function showInfo(element, index, array) {
console.log('element = ' + element + ', index = ' + index + ', array = ' + array);
return false;
}
console.log('return = ' + [4, 6, 8, 12].find(showInfo));
// Output
// element = 4, index = 0, array = 4,6,8,12
// element = 6, index = 1, array = 4,6,8,12
// element = 8, index = 2, array = 4,6,8,12
// element = 12, index = 3, array = 4,6,8,12
// return = undefined
```

View File

@@ -0,0 +1,73 @@
---
title: Array.prototype.findIndex
localeTitle: Array.prototype.findIndex
---
## 信息
`findIndex()`方法返回数组中第一个满足提供的测试函数的元素的索引。否则返回-1。
`findIndex()`方法不会改变调用它的数组。
句法:
```
arr.findIndex(callback[, thisArg])
```
##### 参数
* `callback`
* 函数对数组中的每个值执行,取三个参数:
* `element`
* 当前元素在数组中处理。
* `index`
* 数组中正在处理的当前元素的索引。
* `array`
* 调用了数组findIndex
* `thisArg` (可选)
* 执行回调时要用作此对象的对象。
##### 返回值
如果元素通过测试,则为数组中的索引;否则,-1。
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex)
## 例子
此示例将在数组中找到相应的项并从中返回索引。
```javascript
let items = [
{name: 'books', quantity: 2},
{name: 'movies', quantity: 1},
{name: 'games', quantity: 5}
];
function findMovies(item) {
return item.name === 'movies';
}
console.log(items.findIndex(findMovies));
// Index of 2nd element in the Array is returned,
// so this will result in '1'
```
以下示例显示了回调函数的每个可选参数的输出。这将返回`-1`因为没有任何项将从回调函数返回true。
```javascript
function showInfo(element, index, array) {
console.log('element = ' + element + ', index = ' + index + ', array = ' + array);
return false;
}
console.log('return = ' + [4, 6, 8, 12].findIndex(showInfo));
// Output
// element = 4, index = 0, array = 4,6,8,12
// element = 6, index = 1, array = 4,6,8,12
// element = 8, index = 2, array = 4,6,8,12
// element = 12, index = 3, array = 4,6,8,12
// return = -1
```

View File

@@ -0,0 +1,37 @@
---
title: Array.prototype.forEach
localeTitle: Array.prototype.forEach
---
## Array.prototype.forEach
'forEach'数组方法用于迭代数组中的每个项。该方法在数组Object上调用并传递一个函数该函数在数组中的每个项目上调用。
```javascript
var arr = [1, 2, 3, 4, 5];
arr.forEach(number => console.log(number * 2));
// 2
// 4
// 6
// 8
// 10
```
如果需要引用数组中当前项的索引,则回调函数还可以获取索引的第二个参数。
```javascript
var arr = [1, 2, 3, 4, 5];
arr.forEach((number, i) => console.log(`${number} is at index ${i}`));
// '1 is at index 0'
// '2 is at index 1'
// '3 is at index 2'
// '4 is at index 3'
// '5 is at index 4'
```
#### 更多信息:
[关于Array.prototype.forEach的MDN文章](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach)

View File

@@ -0,0 +1,24 @@
---
title: Array.prototype.includes
localeTitle: Array.prototype.includes
---
## Array.prototype.includes
`includes()`方法确定数组是否包含值。它返回true或false。
它需要两个参数:
1. `searchValue` - 要在数组中搜索的元素。
2. `fromIndex` - 数组中开始搜索proivded `searchValue` 。如果提供负值,则从数组的长度减去负值开始。
### 例
```js
const a = [1, 2, 3];
a.includes(2); // true
a.includes(4); // false
```
#### 更多信息:
[MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/includes)

View File

@@ -0,0 +1,44 @@
---
title: Array.prototype.indexOf
localeTitle: Array.prototype.indexOf
---
## Array.prototype.indexOf
`indexOf()`方法返回可在数组中找到给定元素的第一个索引。如果该元素不存在,则返回-1。
**句法**
```javascript
arr.indexOf(searchElement[, fromIndex])
```
## 参数
* **searchElement**您正在查找的元素
* **fromIndex**可选。要在其中开始搜索的索引。如果fromIndex大于或等于数组的长度则不搜索该数组并且该方法返回-1。如果fromIndex是负数则它会考虑从数组末尾开始的偏移量数组仍然从那里向前搜索。默认值为0表示搜索整个数组。
## 描述
`indexOf`方法以递增索引顺序获取每个数组元素,并使用严格相等( `===` )对`searchElement`进行检查。一旦找到返回`true`的元素,它就会返回其索引。
## 例子
```javascript
var array = [1, 2, 4, 1, 7]
array.indexOf(1); // 0
array.indexOf(7); // 4
array.indexOf(6); // -1
array.indexOf('1'); // -1
array.indexOf('hello'); // -1
array.indexOf(1, 2); // 3
array.indexOf(1, -3); // 3
```
### 更多信息:
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)
[MSDN链接](https://docs.microsoft.com/en-us/scripting/javascript/reference/indexof-method-array-javascript)

View File

@@ -0,0 +1,39 @@
---
title: Array.prototype.join
localeTitle: Array.prototype.join
---
JavaScript数组方法`.join()`将数组的所有元素组合成一个字符串。
**句法**
```javascript
var array = ["Lorem", "Ipsum", "Dolor", "Sit"];
var str = array.join([separator]);
```
## 参数
**分隔器**
可选的。指定用于分隔原始数组的每个元素的字符串。如果分隔符不是字符串则将其转换为字符串。如果未提供separator参数则默认情况下使用逗号分隔数组元素。如果separator是一个空字符串`""` ,则所有数组元素之间的连接都没有分隔符。
## 描述
`.join()`将数组的所有元素连接成一个字符串。如果任何数组元素`undefined`或为`null` ,则该元素将转换为空字符串`""`
## 例子
**使用`.join()`四种不同的方式**
```javascript
var array = ["Lorem", "Ipsum", "Dolor" ,"Sit"];
var join1 = array.join(); /* assigns "Lorem,Ipsum,Dolor,Sit" to join1 variable
(because no separator was provided .join()
defaulted to using a comma) */
var join2 = array.join(", "); // assigns "Lorem, Ipsum, Dolor, Sit" to join2 variable
var join3 = array.join(" + "); // assigns "Lorem + Ipsum + Dolor + Sit" to join3 variable
var join4 = array.join(""); // assigns "LoremIpsumDolorSit" to join4 variable
```
资料来源: [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join)

View File

@@ -0,0 +1,75 @@
---
title: Array.prototype.lastIndexOf
localeTitle: Array.prototype.lastIndexOf
---
## Array.prototype.lastIndexof
`lastIndexOf()`方法返回在数组中可以找到给定元素的最后一个索引,如果不存在则返回-1。从`fromIndex`开始向后搜索数组。
**句法**
```javascript
arr.lastIndexOf(searchElement, fromIndex = arr.length - 1])
```
## 参数
* **searchElement**
* 要在数组中定位的元素。
* **的fromIndex**
* _可选_ 。要开始向后搜索的索引。默认为数组的长度减去1即将搜索整个数组。如果索引大于或等于数组的长度则将搜索整个数组。如果是负数则将其作为距离数组末尾的偏移量。请注意即使索引为负数仍会从后向前搜索数组。如果计算的索引小于0则返回-1即不搜索数组。
[MDN链接](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/lastIndexOf) | [MSDN链接](https://msdn.microsoft.com/en-us/LIBRary/ff679972%28v=vs.94%29.aspx)
## 返回
数组中最后一次出现`searchElement`的索引,如果未找到`searchElement` ,则`searchElement` -1。
## 描述
`lastIndexOf`使用严格相等(与===或`searchElement`运算符使用的方法相同)将`searchElement`与Array的元素进行比较。
## 备注
搜索以降序索引顺序(最后一个成员优先)发生。要按升序搜索,请使用`indexOf`方法。
可选的`fromIndex`参数指定开始搜索的数组索引。如果`fromIndex`大于或等于数组长度,则搜索整个数组。如果`fromIndex`为负数,则搜索从数组长度加上`fromIndex` 。如果计算的索引小于0则返回-1。
## 例子
```javascript
var array = [2, 5, 9, 2];
array.lastIndexOf(2); // 3
array.lastIndexOf(7); // -1
array.lastIndexOf(2, 3); // 3
array.lastIndexOf(2, 2); // 0
array.lastIndexOf(2, -2); // 0
array.lastIndexOf(2, -1); // 3
// Create an array.
var ar = ["ab", "cd", "ef", "ab", "cd"];
// Determine the first location, in descending order, of "cd".
document.write(ar.lastIndexOf("cd") + "<br/>");
// Output: 4
// Find "cd" in descending order, starting at index 2.
document.write(ar.lastIndexOf("cd", 2) + "<br/>");
// Output: 1
// Search for "gh" (which is not found).
document.write(ar.lastIndexOf("gh")+ "<br/>");
// Output: -1
// Find "ab" with a fromIndex argument of -3.
// The search in descending order starts at index 3,
// which is the array length minus 2.
document.write(ar.lastIndexOf("ab", -3) + "<br/>");
// Output: 0
```

Some files were not shown because too many files have changed in this diff Show More