最佳JavaScript示例-程序员宅基地

技术标签: ViewUI  python  java  js  javascript  pig  

JavaScript is the most widely used scripting language on earth. Here are some examples of key syntax patterns in JavaScript.

JavaScript是地球上使用最广泛的脚本语言。 以下是JavaScript中一些关键语法模式的示例。

参数示例 (Argument Example)

The arguments object is an array-like object (in that the structure of the object is similar to that of an array; however it should not be considered an array as it has all the functionality of an object) that stores all of the arguments that you passed to a function and is proprietary to that function in particular.

arguments对象是一个类似于数组的对象 (因为 对象 的结构类似于数组的结构;但是,由于它具有对象的所有功能,因此不应将其视为数组)该对象存储了所有您传递给函数,尤其是该函数专有的。

If you were to pass 3 arguments to a function, say storeNames(), those 3 arguments would be stored inside an object called arguments and it would look like this when we pass the arguments storeNames("Mulder", "Scully", "Alex Krycek") to our function:

如果要将3个参数传递给一个函数,例如storeNames() ,则这3个参数将存储在一个名为arguments的对象中,当我们传递参数storeNames("Mulder", "Scully", "Alex Krycek")的功能:

  • First, we declare a function and make it return the arguments object.

    首先,我们声明一个函数并使它返回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…

    然后,在这种情况下,当我们使用n个参数 3来执行该函数时,它将把对象返回给我们,它看起来像一个数组。 我们可以将其转换为数组,但稍后会更多……

function storeNames() { return arguments; }
// If we execute the following line in the console:
storeNames("Mulder", "Scully", "Alex Kryceck");
// The output will be { '0': 'Mulder', '1': 'Scully', '2': 'Alex Kryceck' }

将其视为数组 (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):

您可以使用arguments[n] (其中n是类似数组的对象中的参数的索引)来调用参数。 但是,如果要将其用作数组以进行迭代或对其应用数组方法,则需要通过声明变量并使用Array.prototype.slice.call方法将其转换为数组 (因为参数不是数组) ):

var args = Array.prototype.slice.call(arguments);

// or the es6 way:
var args = Array.from(arguments)

Since slice() has two (the parameter end is optional) parameters. You can grab a certain portion of the arguments by specifying the beginning and the ending of your portion (using the slice.call() method renders these two parameters optional, not just end). Check out the following code:

由于slice()有两个(参数end是可选的)参数。 您可以通过指定部分的开始和结束来获取参数的特定部分(使用slice.call()方法使这两个参数成为可选参数,而不仅仅是end )。 查看以下代码:

function getGrades() {
    var args = Array.prototype.slice.call(arguments, 1, 3);
    return args;
}

// Let's output this!
console.log(getGrades(90, 100, 75, 40, 89, 95));

// OUTPUT SHOULD BE: //
// [100, 75] <- Why? Because it started from index 1 and stopped at index 3
// so, index 3 (40) wasn't taken into consideration.
//
// If we remove the '3' parameter, leaving just (arguments, 1) we'd get
// every argument from index 1: [100, 75, 40, 89, 95].

Array.slice()的优化问题 (Optimization issues with Array.slice())

There is a little problem: it’s not recommended to use slice in the arguments object (optimization reasons)…

有一个小问题:不建议在arguments对象中使用slice(优化原因)…

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.

重要提示 :请勿切入参数,因为它会阻止JavaScript引擎(例如V8)中的优化。 而是尝试通过遍历arguments对象构造一个新数组。

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:

那么,还有什么其他方法可以将参数转换为数组呢? 我建议使用for循环(而不是for-in循环)。 您可以这样做:

var args = []; // Empty array, at first.
for (var i = 0; i < arguments.length; i++) {
    args.push(arguments[i])
} // Now 'args' is an array that holds your arguments.

For more information on the optimization issues:Optimization Killers: Managing Arguments

有关优化问题的更多信息: 优化杀手:管理参数

ES6 rest参数作为绕过arguments对象的一种方式 (ES6 rest parameter as a way to circumvent the arguments object)

In ES2015/ES6 it is possible to use the rest parameter (...) instead of the arguments object in most places. Say we have the following function (non-ES6):

在ES2015 / ES6中,大多数情况下可以使用rest参数( ... )代替arguments对象。 假设我们具有以下功能(非ES6):

function getIntoAnArgument() {
    var args = arguments.slice();
    args.forEach(function(arg) {
        console.log(arg);
    });
}

That function can be replaced in ES6 by:

该功能可以在ES6中替换为:

function getIntoAnArgument(...args) {
    args.forEach(arg => console.log(arg));
}

Note that we also used an arrow function to shorten the forEach callback!

请注意,我们还使用了箭头功能来缩短forEach回调!

The arguments object is not available inside the body of an arrow function.

arguments对象在箭头函数的主体内不可用。

The rest parameter must always come as the last argument in your function definition.function getIntoAnArgument(arg1, arg2, arg3, ...restOfArgs /*no more arguments allowed here*/) { //function body }

rest参数必须始终作为函数定义中的最后一个参数。 function getIntoAnArgument(arg1, arg2, arg3, ...restOfArgs /*no more arguments allowed here*/) { //function body }

算术运算示例 (Arithmetic Operation Example)

JavaScript provides the user with five arithmetic operators: +, -, *, / and %. The operators are for addition, subtraction, multiplication, division and remainder, respectively.

JavaScript为用户提供了五个算术运算符: +-*/% 。 运算符分别用于加法,减法,乘法,除法和余数。

加成 (Addition)

Syntax

句法

a + b

a + b

Usage

用法

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"

Hint: There is a handy increment operator that is a great shortcut when you’re adding numbers by 1.

提示:有一个方便的增量运算符,当您将数字加1时,这是一个很好的捷径。

减法 (Subtraction)

Syntax

句法

a - b

a - b

Usage

用法

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)

Hint: There is a handy decrement operator that is a great shortcut when you’re subtracting numbers by 1.

提示:有一个方便的减量运算符,当您将数字减1时,这是一个很好的捷径。

乘法 (Multiplication)

Syntax

句法

a * b

a * b

Usage

用法

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

Hint: When making calculations it is possible to use parentheses to prioritize which numbers should be multiplied together.

提示:进行计算时,可以使用括号来确定应将哪些数字相乘的优先级。

(Division)

Syntax

句法

a / b

a / b

Usage

用法

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

(Remainder)

Syntax

句法

a % b

a % b

Usage

用法

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

增量 (Increment)

Syntax

句法

a++ or ++a

a++ or ++a

Usage

用法

// Postfix 
x = 3; // declare a variable 
y = x++; // y = 4, x = 3 

// Prefix 
var a = 2; 
b = ++a; // a = 3, b = 3

减量 (Decrement)

Syntax

句法

a-- or --a

a-- or --a

Usage

用法

// Postfix 
x = 3; // declare a variable 
y = x—; // y = 3, x = 3 

// Prefix 
var a = 2; 
b = —a; // a = 1, b = 1

Important: As you can see, you cannot perform any sort of operations on Infinity.

重要提示:如您所见,您无法Infinity上执行任何类型的操作。

箭头功能示例 (Arrow Function Example)

Arrow functions are a new ES6 syntax for writing JavaScript function expressions. The shorter syntax saves time, as well as simplifying the function scope.

箭头函数是用于编写JavaScript函数表达式的新ES6语法。 较短的语法可节省时间,并简化功能范围。

什么是箭头功能? (What are arrow functions?)

An arrow function expression is a more concise syntax for writing function expressions using a “fat arrow” token (=>).

箭头函数表达式是一种更简洁的语法,用于使用“胖箭头”标记( => )编写函数表达式。

基本语法 (The basic syntax)

Below is a basic example of an arrow function:

以下是箭头功能的基本示例:

// 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;

You no longer need the function and return keywords, or even the curly brackets.

您不再需要functionreturn关键字,甚至不需要大括号。

简化this (A simplified this)

Before arrow functions, new functions defined their own this value. To use this inside a traditional function expression, we have to write a workaround like so:

在箭头函数之前,新函数定义了自己的this值。 要在传统函数表达式中使用this方法,我们必须编写如下解决方法:

// 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);
}

An arrow function doesn’t define its own this value, it inherits this from the enclosing function:

箭头功能没有定义自己的this价值,它继承了this从封闭功能:

// ES6 syntax
function Person(){
  this.age = 0;

  setInterval(() => {
    // `this` now refers to the Person object, brilliant!
    this.age++;
  }, 1000);
}

var p = new Person();

赋值运算符 (Assignment Operators)

赋值运算符示例 (Assignment Operator Example)

Assignment operators, as the name suggests, assign (or re-assign) values to a variable. While there are quite a few variations on the assignment operators, they all build off of the basic assignment operator.

顾名思义,赋值运算符将值分配(或重新分配)给变量。 尽管赋值运算符有很多变体,但它们都是在基本赋值运算符的基础上构建的。

Syntax = y;DescriptionNecessityxVariableRequired=Assignment operatorRequiredyValue to assign to variableRequired

语法= y; DescriptionNecessityxVariableRequired =要分配给variableRequired的赋值运算符RequiredyValue

例子 (Examples)

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

变化 (Variations)

The other assignment operators are a shorthand for performing some operation using the variable (indicated by x above) and value (indicated by y above) and then assigning the result to the variable itself.

其他赋值运算符是使用变量(在上面用x表示)和值(在上面y表示)执行某种运算,然后将结果赋给变量本身的简写形式。

For example, below is the syntax for the addition assignment operator:

例如,以下是加法赋值运算符的语法:

x += y;

This is the same as applying the addition operator and reassigning the sum to the original variable (that is, x), which can be expressed by the following code:

这与应用加法运算符并将总和重新分配给原始变量(即x)相同,可以通过以下代码表示:

x = x + y;

To illustrate this using actual values, here is another example of using the addition assignment operator:

为了使用实际值进行说明,这是另一个使用加法赋值运算符的示例:

let myVar = 5;   // value of myVar: 5
myVar += 7;   // value of myVar: 12 = 5 + 7

JavaScript赋值运算符的完整列表 (Complete list of JavaScript’s assignment operators)

Operator Syntax Long version
Assignment x = y x = y
Addition assignment x += y x = x + y
Subtraction assignment x -= y x = x - y
Multiplication assignment x *= y x = x * y
Division assignment x /= y x = x / y
Remainder assignment x %= y x = x % y
Exponentiation assignment x **= y x = x ** y
Left shift assignment x <<= y x = x << y
Right shift assignment x >>= y x = x >> y
Unsigned right shift assignment x >>>= y x = x >>> y
Bitwise AND assignment x &= y x = x & y
Bitwise XOR assignment x ^= y x = x ^ y
Bitwise OR assignment x |= y x = x | y
操作员 句法 长版
分配 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 = 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 = x&y
按位XOR分配 x ^ = y x = x ^ y
按位或分配 x | = y x = x | ÿ

布尔型示例 (Boolean Example)

Booleans are a primitive datatype commonly used in computer programming languages. By definition, a boolean has two possible values: true or false.

布尔值是计算机编程语言中常用的原始数据类型。 根据定义,布尔值有两个可能的值: truefalse

In JavaScript, there is often implicit type coercion to boolean. If for example you have an if statement which checks a certain expression, that expression will be coerced to a boolean:

在JavaScript中,布尔值通常存在隐式类型强制。 例如,如果您有一个if语句检查某个表达式,则该表达式将被强制转换为布尔值:

var a = 'a string';
if (a) {
  console.log(a); // logs 'a string'
}

There are only a few values that will be coerced to false:

只有少数几个值会被强制设置为false:

  • false (not really coerced, as it already is false)

    假(不是真的被强制,因为它已经是假的)
  • null

    空值
  • undefined

    未定义
  • NaN

    N
  • 0

    0
  • ” (empty string)

    ”(空字符串)

All other values will be coerced to true. When a value is coerced to a boolean, we also call that either ‘falsy’ or ‘truthy’.

所有其他值将被强制为true。 当值强制为布尔值时,我们也称其为“ falsy”或“ truthy”。

One way that type coercion is used is with the use of the or (||) and and (&&) operators:

使用类型强制的一种方式是使用or( || )和and( && )运算符:

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'

As you can see, the or operator checks the first operand. If this is true or truthy, it returns it immediately (which is why we get ‘word’ in the first case & true in the second case). If it is not true or truthy, it returns the second operand (which is why we get ‘word’ in the third case).

如您所见, or运算符检查第一个操作数。 如果这是对还是错,它会立即返回它(这就是为什么我们在第一种情况下得到“单词”而在第二种情况下得到true的原因)。 如果它不是对或不对,则返回第二个操作数(这就是为什么在第三种情况下我们得到“单词”的原因)。

With the and operator it works in a similar way, but for ‘and’ to be true, both operands need to be truthy. So it will always return the second operand if both are true/truthy, otherwise it will return false. That is why in the fourth case we get true and in the last case we get ‘word’.

使用and运算符,其工作方式类似,但是要使“ and”为真,两个操作数都必须为真。 因此,如果两个操作数均为true / true,它将始终返回第二个操作数,否则将返回false。 这就是为什么在第四种情况下我们为真,而在最后一种情况下我们为“单词”的原因。

布尔对象 (The Boolean Object)

There is also a native JavaScript Boolean object that wraps around a value and converts the first parameter to a boolean value. If a value is omitted or falsy –0, -0, null, false, NaN, undefined, or an empty string ("") – the object's value is false. Pass all other values, including the string "false", and the object's value is set to true.

还有一个本地JavaScript Boolean对象,该对象包装一个值并将第一个参数转换为布尔值。 如果省略或伪造的值–0,-0, nullfalseNaNundefined或空字符串( "" )–对象的值为false。 传递所有其他值,包括字符串"false" ,并且该对象的值设置为true。

Note that primitive Boolean values (true and false) are different than those of the Boolean object.

请注意,原始布尔值( truefalse )与布尔对象的值不同。

更多细节 (More Details)

Remember that any object, the value of which is not undefined or null, evaluates to true if used in a conditional statement. For example, even though this Boolean object is explicitly set to false, it evaluates to true and the code is executed:

请记住,如果在条件语句中使用其值不是undefinednull任何对象,则其值为true。 例如,即使此Boolean对象被显式设置为false,它也将评估为true并执行代码:

var greeting = new Boolean(false);
if (greeting) {
  console.log("Hello world");
}

// Hello world

This doesn't apply to boolean primitives:

这不适用于布尔基元:

var greeting = false;
if (greeting) {
  console.log("Hello world"); // code will not run
}

To convert a non-boolean value to a boolean, use Boolean as a function rather than as an object:

要将非布尔值转换为布尔值,请使用Boolean作为函数而不是对象:

var x = Boolean(expression);     // preferred use as a function
var x = new Boolean(expression); // don't do it this way

回调函数 (Callback Functions)

This section gives a brief introduction to the concept and usage of callback functions in JavaScript.

本节简要介绍了JavaScript中回调函数的概念和用法。

功能就是对象 (Functions are Objects)

The first thing we need to know is that in JavaScript, functions are first-class objects. As such, we can work with them in the same way we work with other objects, like assigning them to variables and passing them as arguments into other functions. This is important, because it’s the latter technique that allows us to extend functionality in our applications.

我们需要知道的第一件事是,在JavaScript中,函数是一流的对象。 这样,我们可以像处理其他对象一样使用它们,例如将它们分配给变量并将它们作为参数传递给其他函数。 这很重要,因为后一种技术使我们能够扩展应用程序中的功能。

回调函数示例 (Callback Function Example)

A callback function is a function that is passed as an argument to another function, to be “called back” at a later time.

回调函数是一个作为参数传递给另一个函数的函数,以后将被“回调”。

A function that accepts other functions as arguments is called a higher-order function, which contains the logic for when the callback function gets executed. It’s the combination of these two that allow us to extend our functionality.

接受其他函数作为参数的函数被称为高阶函数 ,其包含所述回调函数被执行为逻辑。 两者的结合使我们能够扩展功能。

To illustrate callbacks, let’s start with a simple example:

为了说明回调,让我们从一个简单的示例开始:

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!

In the above example, createQuote is the higher-order function, which accepts two arguments, the second one being the callback. The logQuote function is being used to pass in as our callback function. When we execute the createQuote function (1), notice that we are not appending parentheses to logQuote when we pass it in as an argument. This is because we do not want to execute our callback function right away, we simply want to pass the function definition along to the higher-order function so that it can be executed later.

在上面的示例中, createQuote是高阶函数,它接受两个参数,第二个参数是回调。 logQuote函数被用作我们的回调函数。 当我们执行createQuote函数(1)时 ,请注意,当我们将logQuote作为参数传递时,没有在logQuote 后面加上括号。 这是因为我们不想立即执行回调函数,我们只想将函数定义传递给高阶函数,以便以后可以执行。

Also, we need to ensure that if the callback function we pass in expects arguments,  we supply those arguments when executing the callback (2). In the above example, that would be the callback(myQuote);statement, since we know that logQuote expects a quote to be passed in.

另外,我们需要确保如果传入的回调函数期望参数,则在执行回调(2)时提供这些参数。 在上面的示例中,这将是callback(myQuote); 语句,因为我们知道logQuote希望传递一个报价。

Additionally, we can pass in anonymous functions as callbacks. The below call to createQuote would have the same result as the above example:

此外,我们可以将匿名函数作为回调传递。 以下对createQuote调用将具有与以上示例相同的结果:

createQuote("eat your vegetables!", function(quote){ 
  console.log(quote); 
});

Incidentally, you don’t have to use the word “callback” as the name of your argument. JavaScript just needs to know that it’s the correct argument name. Based on the above example, the below function will behave in exactly the same manner.

顺便说一句,你不必用“回拨”作为参数的名称。 JavaScript只需要知道它是正确的参数名称即可。 根据上面的示例,下面的函数将以完全相同的方式运行。

function createQuote(quote, functionToCall) { 
  var myQuote = "Like I always say, " + quote;
  functionToCall(myQuote);
}

为什么要使用回调? (Why use Callbacks?)

Most of the time we are creating programs and applications that operate in a synchronous manner. In other words, some of our operations are started only after the preceding ones have completed.

大多数时候,我们正在创建以同步方式运行的程序和应用程序。 换句话说,我们的某些操作仅在上述操作完成后才开始。

Often when we request data from other sources, such as an external API, we don’t always know when our data will be served back. In these instances we want to wait for the response, but we don’t always want our entire application grinding to a halt while our data is being fetched. These situations are where callback functions come in handy.

通常,当我们从其他来源(例如外部API)请求数据时,我们并不总是知道何时将数据送回。 在这些情况下,我们希望等待响应,但是我们并不总是希望在获取数据时整个应用程序停止运行。 在这些情况下,回调函数非常有用。

Let’s take a look at an example that simulates a request to a server:

让我们看一个模拟对服务器请求的示例:

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!

In the above example, we make a mock request to a server. After 5 seconds elapse, the response is modified and then our callback function getResults gets executed. To see this in action, you can copy/paste the above code into your browser’s developer tool and execute it.

在上面的示例中,我们向服务器发出了模拟请求。 5秒钟后,将修改响应,然后执行我们的回调函数getResults 。 要查看实际效果,您可以将以上代码复制/粘贴到浏览器的开发人员工具中并执行。

Also, if you are already familiar with setTimeout, then you’ve been using callback functions all along. The anonymous function argument passed into the above example’s setTimeout function call is also a callback! So the example’s original callback is actually executed by another callback. Be careful not to nest too many callbacks if you can help it, as this can lead to something called “callback hell”! As the name implies, it isn’t a joy to deal with.

另外,如果您已经熟悉setTimeout ,那么您一直都在使用回调函数。 传递到上述示例的setTimeout函数调用中的匿名函数参数也是回调! 因此,该示例的原始回调实际上是由另一个回调执行的。 如果可以帮助,请注意不要嵌套太多回调,因为这可能会导致“回调地狱”! 顾名思义,处理它并不是一件愉快的事情。

JavaScript类示例 (JavaScript Class Example)

JavaScript does not have the concept of classes inherently.

JavaScript本质上没有类的概念。

But we could simulate the functionalities of a class by taking advantage of the prototypal nature of JavaScript.

但是,我们可以利用JavaScript的原型性质来模拟类的功能。

This section assumes that you have a basic understanding of prototypes.

本节假定您对原型有基本的了解。

For the sake of clarity, let us assume that we want to create a class which can do the following

为了清楚起见,让我们假设我们要创建一个可以执行以下操作的类

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

使用类关键字 (Using class keyword)

Like in any other programming language, you can now use the class keyword to create a class.

与其他任何编程语言一样,您现在可以使用class关键字创建一个类。

This is not supported in older browsers and was introduced in ECMAScript 2015.

较旧的浏览器不支持此功能,它是ECMAScript 2015中引入的。

class is just a syntactic sugar over JavaScript’s existing prototype-based inheritance model.

class只是JavaScript现有的基于原型的继承模型的语法糖。

In general, programmers use the following ways to create a class in JavaScript.

通常,程序员使用以下方法在JavaScript中创建类。

使用添加到原型的方法: (Using methods added to prototypes:)

Here, all the methods are added to prototype

在这里,所有方法都添加到原型中

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);
    }
})

You could also write prototype methods over function Person as below:

您还可以通过功能Person编写原型方法,如下所示:

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);
    }

}

使用内部添加的方法 (Using methods added internally)

Here the methods are added internally instead of prototype:

在这里,这些方法是在内部添加的,而不是在原型中添加的:

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);
        }
    })
}

用符号隐藏类中的细节 (Hiding details in classes with symbols)

Most often, some properties and methods have to be hidden to prevent access from outside the function.

大多数情况下,必须隐藏某些属性和方法以防止从函数外部进行访问。

With classes, to obtain this functionality, one way to do this is by using symbols. Symbol is a new built-in type of JavaScript, which can be invoked to give a new symbol value. Every Symbol is unique and can be used as a key on object.

对于类,要获得此功能,一种方法是使用符号。 Symbol是一种新的内置JavaScript类型,可以调用它来赋予新的Symbol值。 每个符号都是唯一的,可用作对象上的键。

So one use case of symbols is that you can add something to an object you might not own, and you might not want to collide with any other keys of object. Therefore, creating a new one and adding it as a property to that object using symbol is the safest. Also, when symbol value is added to an object, no one else will know how to get it.

因此,符号的一种使用情况是您可以向您可能不拥有的对象添加某些东西,并且可能不想与该对象的任何其他键冲突。 因此,使用符号创建一个新对象并将其作为属性添加到该对象是最安全的。 同样,将符号值添加到对象时,没有人会知道如何获取它。

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);
    }

JavaScript封闭范例 (JavaScript Closure Example)

A closure is the combination of a function and the lexical environment (scope) within which that function was declared. Closures are a fundamental and powerful property of Javascript. This section discusses the ‘how’ and ‘why’ about Closures:

闭包是函数和在其中声明该函数的词法环境(范围)的组合。 闭包是Javascript的基本功能。 本节讨论关闭的“方式”和“原因”:

(Example)

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

另一个例子 (Another Example)

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 } ]

The closure ‘remembers’ the environment in which it was created. This environment consists of any local variables that were in-scope at the time the closure was created.

闭包“记住”创建它的环境。 此环境由创建关闭时在范围内的所有局部变量组成。

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

Closures are useful because they let you ‘remember’ data and then let you operate on that data through returned functions. This allows Javascript to emulate private methods that are found in other programming languages. Private methods are useful for restricting access to code as well as managing your global namespace.

闭包很有用,因为它们可以让您“记住”数据,然后让您通过返回的函数对数据进行操作。 这允许Javascript模拟其他编程语言中找到的私有方法。 私有方法对于限制对代码的访问以及管理全局名称空间很有用。

私有变量和方法 (Private variables and methods)

Closures can also be used to encapsulate private data/methods. Take a look at this example:

闭包也可以用于封装私有数据/方法。 看一下这个例子:

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

In this example, we won’t be able to access balance from anywhere outside of the bankAccount function, which means we’ve just created a private variable.

在此示例中,我们将无法从bankAccount函数之外的任何位置访问balance ,这意味着我们仅创建了一个私有变量。

Where’s the closure? Well, think about what bankAccount() is returning. It actually returns an Object with a bunch of functions inside it, and yet when we call account.getBalance(), the function is able to “remember” its initial reference to balance.

封闭在哪里? 好吧,考虑一下bankAccount()返回什么。 实际上,它返回一个内部带有一堆函数的Object,但是当我们调用account.getBalance() ,该函数能够“记住”其对balance初始引用。

That is the power of the closure, where a function “remembers” its lexical scope (compile time scope), even when the function is executed outside that lexical scope.

这就是闭包的强大之处,即使函数在该词法范围之外执行,函数也“记住”其词法范围(编译时范围)。

模拟块作用域变量 (Emulating block-scoped variables)

Javascript did not have a concept of block-scoped variables. Meaning that when defining a variable inside a for-loop, for example, this variable was visible from outside the for-loop as well. So how can closures help us solve this problem? Let’s take a look.

Javascript没有块范围变量的概念。 这意味着,例如,在for循环内部定义变量时,也可以从for循环外部看到此变量。 那么闭包如何帮助我们解决这个问题呢? 让我们来看看。

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
    }

Since the variable i does not have block-scope, it’s value within all three functions was updated with the loop counter and created malicious values. Closures can help us solve this issue by creating a snapshot of the environment the function was in when it was created, preserving its state.

由于变量i没有块作用域,因此使用循环计数器更新了这三个函数中的值并创建了恶意值。 闭包可以通过创建函数创建时所在环境的快照并保留其状态来帮助我们解决此问题。

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
    }

The later versions of Javascript (ES6+) have a new keyword called let which can be used to give the variable a blockscope. There are also many functions (forEach) and entire libraries (lodash.js) that are dedicated to solving such problems as the ones explained above. They can certainly boost your productivity, however it remains extremely important to have knowledge of all these issues when attempting to create something big.

更高版本的Javascript(ES6 +)具有一个名为let的新关键字,该关键字可用于为变量赋予功能块。 还有许多函数(forEach)和整个库(lodash.js)专门用于解决上述问题。 它们当然可以提高您的生产率,但是在尝试创建大型产品时了解所有这些问题仍然非常重要。

Closures have many special applications that are useful when creating large Javascript programs.

闭包有许多特殊的应用程序,在创建大型Javascript程序时非常有用。

  1. Emulating private variables or encapsulation

    模拟私有变量或封装
  2. Making Asynchronous server side calls

    进行异步服务器端调用
  3. Creating a block-scoped variable.

    创建一个块作用域变量。

模拟私有变量 (Emulating private variables)

Unlike many other languages, Javascript does not have a mechanism which allows you to create encapsulated instance variables within an object. Having public instance variables can cause a lot of problems when building medium to large programs. However with closures, this problem can be mitigated.

与许多其他语言不同,Javascript没有允许您在对象内创建封装的实例变量的机制。 在构建中型到大型程序时,拥有公共实例变量会导致很多问题。 但是,使用闭包可以缓解此问题。

Much like in the previous example, you can build functions which return object literals with methods that have access to the object’s local variables without exposing them. Thus, making them effectively private.

与上一个示例非常相似,您可以构建函数,这些函数使用可以访问对象的局部变量而无需暴露它们的方法来返回对象文字。 因此,将它们有效地私有化。

Closures can also help you manage your global namespace to avoid collisions with globally shared data. Usually, all global variables are shared between all scripts in your project, which will definitely give you a lot of trouble when building medium to large programs.

闭包还可以帮助您管理全局名称空间,以避免与全局共享数据发生冲突。 通常,所有全局变量在项目中的所有脚本之间共享,这在构建中型到大型程序时肯定会给您带来很多麻烦。

That is why library and module authors use closures to hide an entire module’s methods and data. This is called the module pattern, it uses an immediately invoked function expression which exports only certain functionality to the outside world, significantly reducing the amount of global references.

这就是为什么库和模块作者使用闭包来隐藏整个模块的方法和数据的原因。 这称为模块模式,它使用立即调用的函数表达式,该函数表达式仅将某些功能导出到外界,从而大大减少了全局引用的数量。

Here’s a short sample of a module skeleton.

这是模块骨架的简短示例。

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

Closures are useful for capturing new instances of private variables contained in the ‘remembered’ environment, and those variables can only be accessed through the returned function or methods.

闭包对于捕获“记住的”环境中包含的私有变量的新实例很有用,这些变量只能通过返回的函数或方法进行访问。

JavaScript注释示例 (JavaScript Comment Example)

Programmers use comments to add hints, notes, suggestions, or warnings to their source code; they have no effect on the actual output of the code. Comments can be very helpful in explaining the intent of what your code is or should be doing.

程序员使用注释在其源代码中添加提示,注释,建议或警告。 它们对代码的实际输出没有影响。 注释对于解释代码的意图或应该做什么非常有帮助。

It is always best practice when starting out to comment more often than not, as it can help those reading your code to understand what exactly your code is intending to do.

最好总是在开始注释时多加注释,因为它可以帮助阅读您的代码的人理解您的代码打算做什么。

JavaScript has two ways of assigning comments in its code.

JavaScript有两种在代码中分配注释的方式。

The first way is the // comment; all text following // on the same line into a comment. For example:

第一种方法是//注释; //在同一行之后//后面的所有文本都变成注释。 例如:

function hello() {
  // This is a one line JavaScript comment
  console.log("Hello world!");
}
hello();

The second way is the /* */ comment, which can be used for both single-line and multi-line comments. For example:

第二种方法是/* */注释,它可以用于单行和多行注释。 例如:

function hello() {
  /* This is a one line JavaScript comment */
  console.log("Hello world!");
}
hello();
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();

You can also prevent execution of Javascript code just commeting the code lines like this:

您还可以像这样修改代码行来阻止执行Javascript代码:

function hello() {
  /*console.log("Hello world!");*/
}
hello();
更多信息: (More Information:)

How To Write Comments in JavaScript

如何用JavaScript编写注释

许多IDE带有键盘快捷键来注释掉行。 (Many IDEs come with a keyboard shortcut to comment out lines.)

  1. Highlight text to be commented

    突出显示要评论的文本
  2. Mac: Push Command(Apple Key) & "/"

    Mac:推送命令(Apple键)和“ /”
  3. Windows: Push Control & "/"

    Windows:推送控制和“ /”
  4. You can also uncomment code by doing the same steps

    您也可以通过执行相同的步骤来取消注释代码

A shortcut to comment out a section of Javascript in many code editors is to highlight the lines of code you want to comment out, then press `Cmd/Ctrl + /`.

在许多代码编辑器中,注释掉一段Javascript的快捷方式是突出显示要注释掉的代码行,然后按`Cmd / Ctrl + /`。

Comments are also very helpful for code testing as you can prevent a certain code-line/block from running:

注释对于代码测试也非常有帮助,因为您可以阻止某些代码行/块运行:

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比较运算符示例 (JavaScript Comparison Operator Example)

JavaScript has both strict and type–converting comparisons.

JavaScript具有严格类型转换的比较。

  • The strict comparison (===) only evaluates to true if both operands are the same type.

    如果两个操作数的类型相同,则严格比较( === )的结果为true。

  • The abstract comparison (==) attempts to convert both operands to the same type before comparing them.

    抽象比较( == )尝试在比较它们之前将两个操作数转换为相同类型。

  • With relational abstract comparisons (<=), both operands are converted to primitives, then to the same type before comparison.

    使用关系抽象比较( <= ),两个操作数都将转换为基元,然后在比较之前转换为相同的类型。

  • Strings are compared using Unicode values based on standard ordering.

    使用基于标准顺序的Unicode值比较字符串。

比较功能: (Features of comparisons:)

  • Two strings are considered strictly equal when they have the characters in the same sequence and the same length.

    当两个字符串具有相同顺序和相同长度的字符时,它们被视为严格相等。
  • Two numbers are considered strictly equal when they are the both of the type number and are numerically equal. This means that both 0 and -0 are strictly equal since they both evaluate to 0. Note that NaN is a special value and is not equal to anything, including NaN.

    当两个数字既是类型数字又是数字相等时,则被视为严格相等。 这意味着0-0严格相等,因为它们的-0均为0 。 请注意, NaN是一个特殊值,并且不等于任何值,包括NaN

  • Two Boolean operands are considered strictly equal if both are true or false.

    如果两个布尔操作数均为truefalse则它们被视为严格相等。

  • Two objects are never considered equal in both strict or abstract comparisons.

    在严格比较或抽象比较中,永远不要将两个对象视为相等。
  • Expressions that compare objects are only considered true if the operands both reference the same exact object instance.

    仅当操作数都引用相同的确切对象实例时,才将比较对象的表达式视为真。
  • Null and undefined are both considered strictly equal to themselves (null === null) and abstractly equal to each other (null == undefined)

    Null和undefined都被认为严格等于自己( null === null )并且抽象地彼此相等( null == undefined )

平等经营者 (Equality operators)

平等(==) (Equality (==))

The equality operator first converts operands that are not of the same type, then strictly compares them to one another.

相等运算符首先转换不同类型的操作数,然后严格将它们相互比较。

句法 (Syntax)
x == y
例子 (Examples)
1   ==  1        // true
"1"  ==  1        // true
 1   == '1'       // true
 0   == false     // true
 0   == null      // false

 0   == undefined   // false
 null  == undefined // true

不等式(!=) (Inequality (!=))

The inequality operator evaluates to true if both operands are not equal. If the operands are not the same type, it will try to convert them to the same type before making the comparison.

如果两个操作数不相等,则不等式运算符的计算结果为true。 如果操作数不是同一类型,它将在进行比较之前尝试将它们转换为相同类型。

句法 (Syntax)
x != y
例子 (Examples)
1 !=   2     // true
1 !=  "1"    // false
1 !=  '1'    // false
1 !=  true   // false
0 !=  false  // false

身份/严格平等(===) (Identity / strict equality (===))

The identity or strict equality operator returns true if both operands are strictly equal in terms of value and type. Unlike the equality operator (==), it will not attempt to convert the operands to the same type.

如果两个操作数的值和类型严格相等,则identity或严格相等运算符将返回true。 与相等运算符( == )不同,它不会尝试将操作数转换为相同类型。

句法 (Syntax)
x === y
例子 (Examples)
3 === 3   // true
3 === '3' // false

非身份/严格不平等(!==) (Non-identity / strict inequality (!==))

The non-identity or strict inequality operator returns true if both operands are not strictly equal in terms of value or type.

如果两个操作数的值或类型都不严格相等,则非同一性或严格不等式运算符将返回true。

句法 (Syntax)
x !== y
例子 (Examples)
3 !== '3' // true
4 !== 3   // true

关系运算符 (Relational operators)

大于运算符(>) (Greater than operator (>))

The greater than operator returns true if the operand on the left is greater than the one on the right.

如果左侧的操作数大于右侧的操作数,则大于运算符将返回true。

句法 (Syntax)
x > y
例子 (Examples)
4 > 3 // true

大于或等于运算符(> =) (Greater than or equal operator (>=))

The greater than or equal operator returns true if the operand on the left is greater than or equal to the one on the right.

如果左侧的操作数大于或等于右侧的操作数,则大于或等于运算符将返回true。

句法 (Syntax)
x >= y
例子 (Examples)
4 >= 3 // true
3 >= 3 // true

小于运算符(<) (Less than operator (<))

The less than operator returns true if the operand on the left is less than the one on the right.

如果左侧的操作数小于右侧的操作数,则小于操作符将返回true。

句法 (Syntax)
x < y
例子 (Examples)
3 < 4 // true

小于或等于运算符(<=) (Less than or equal operator (<=))

The less than or equal operator returns true if the operand on the left is less than or equal to the one on the right.

如果左侧的操作数小于或等于右侧的操作数,则小于或等于运算符返回true。

句法 (Syntax)
x <= y
例子 (Examples)
3 <= 4 // true

JavaScript表单验证示例 (JavaScript Form Validation Example)

Form validation used to occur at the server, after the client had entered all the necessary data and then pressed the Submit button. If the data entered by a client was incorrect or was simply missing, the server would have to send all the data back to the client and request that the form be resubmitted with correct information. This was really a lengthy process which used to put a lot of burden on the server.

客户端输入所有必要的数据,然后按Submit按钮后,表单验证通常在服务器上进行。 如果客户端输入的数据不正确或完全丢失,则服务器将必须将所有数据发送回客户端,并要求重新提交带有正确信息的表单。 这确实是一个漫长的过程,曾经给服务器带来很多负担。

JavaScript provides a way to validate form’s data on the client’s computer before sending it to the web server. Form validation generally performs two functions:

JavaScript提供了一种在将表单数据发送到Web服务器之前在客户端计算机上对其进行验证的方法。 表单验证通常执行两个功能:

基本验证 (Basic Validation)

First of all, the form must be checked to make sure all the mandatory fields are filled in. It just requires a loop through each field in the form to check for data.

首先,必须检查表单以确保填写了所有必填字段。它只需要循环遍历表单中的每个字段以检查数据。

数据格式验证 (Data Format Validation)

Secondly, the data that is entered must be checked for correct form and value. Your code must include appropriate logic to test the correctness of the data.

其次,必须检查输入的数据的正确形式和值。 您的代码必须包含适当的逻辑以测试数据的正确性。

例: (Example:)
<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>
输出量 (Output)

Have a look here.

在这里看看。

基本表格验证 (Basic Form Validation)

First let us see how to do a basic form validation. In the above form, we are calling validate() to validate data when the onsubmit event is occurring. The following code shows the implementation of this validate()function.

首先让我们看看如何进行基本的表单验证。 在上述形式中,我们在发生onsubmit事件时调用validate()来验证数据。 以下代码显示了validate()函数的实现。

<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>
输出量 (Output)

Have a look here.

在这里看看。

数据格式验证 (Data Format Validation)

Now we will see how we can validate our entered form data before submitting it to the web server.

现在,我们将看到如何在将输入的表单数据提交到Web服务器之前对其进行验证。

The following example shows how to validate an entered email address. An email address must contain at least an ‘@’ sign and a dot (.). Also, the ‘@’ must not be the first character of the email address, and the last dot must at least be one character after the ‘@’ sign.

以下示例显示了如何验证输入的电子邮件地址。 电子邮件地址必须至少包含一个'@'符号和一个点(。)。 另外,“ @”一定不能是电子邮件地址的第一个字符,最后一个点必须至少是“ @”符号后的一个字符。

例: (Example:)
<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>
输出量 (Output)

Have a look here.

在这里看看。

HTML5表单约束 (HTML5 Form Constraints)

Some of the commonly used HTML5 constraints for <input> are the type attribute (e.g. type="password"), maxlength, required and disabled. A less commonly used constraint is the pattern attribute that takes a JavaScript regular expression.

<input>一些常用HTML5约束是type属性(例如type="password" ), maxlengthrequireddisabled 。 较少使用的约束是采用JavaScript正则表达式的pattern属性。

JavaScript If语句示例 (JavaScript If statement example)

The if statement executes a statement if a specified condition is true. If the condition is false, another statement can be executed using the else statement.

if指定条件为trueif语句执行一条语句。 如果条件为false ,则可以使用else语句执行另一条语句。

Note: The else statement is optional.

注意: else语句是可选的。

if (condition)
    /* do something */
else
    /* do something else */

Multiple if...else statements can be chained to create an else if clause. This specifies a new condition to test and can be repeated to test multiple conditions, checking until a true statement is presented to execute.

可以将多个if...else语句链接起来以创建else if子句。 这指定了一个要测试的新条件,可以重复以测试多个条件,直到检查出要执行的真语句为止。

if (condition1)
    /* do something */
else if (condition2)
    /* do something else */
else if (condition3)
    /* do something else */
else
    /* final statement */

Note: If you want to execute more than one statement in the if, else or else if part, curly braces are required around the statements:

注意:如果要在ifelseelse if部分中执行多个语句,则需要在语句周围使用花括号:

if (condition) {
    /* do */
    /* something */
    /* with multiple statements */
} else {
    /* do something */
    /* else */
}

MDN link | MSDN link

MDN链接 | MSDN链接

例子 (Examples)

Using if...else:

使用 if...else

// 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;

Using else if:

在以下情况下使用 else if

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";
}

JavaScript原型示例 (JavaScript Prototype Example)

JavaScript is a prototype-based language, therefore understanding the prototype object is one of the most important concepts which JavaScript practitioners need to know.

JavaScript是基于原型的语言,因此了解原型对象是JavaScript从业人员需要了解的最重要的概念之一。

This section will give you a short overview of the Prototype object through various examples. Before reading this part, you will need to have a basic understanding of the this reference in JavaScript.

本节将通过各种示例简要概述Prototype对象。 在阅读本部分之前,您需要对JavaScript中的this引用有基本的了解。

原型对象 (Prototype object)

For the sake of clarity, let’s examine the following example:

为了清楚起见,让我们研究以下示例:

function Point2D(x, y) {
  this.x = x;
  this.y = y;
}

As Point2D function is declared, a default property named prototype will be created for it (note that, in JavaScript, a function is also an object).

声明Point2D函数后,将为其创建一个名为prototype的默认属性(请注意,在JavaScript中,函数也是一个对象)。

The prototype property is an object which contains a constructorproperty and its value is Point2D function: Point2D.prototype.constructor = Point2D. And when you call Point2D with new keyword, newly created objects will inherit all properties from Point2D.prototype.

prototype属性是一个包含constructor属性的对象,其值为Point2D函数: Point2D.prototype.constructor = Point2D 。 当您使用new关键字调用Point2D时, 新创建的对象将继承 Point2D.prototype 所有属性

To check that, you can add a method named move into Point2D.prototype as follows:

要进行检查,可以在Point2D.prototype添加一个名为move的方法,如下所示:

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

The Point2D.prototype is called prototype object or prototype of p1 object and for any other object created with new Point2D(...) syntax. You can add more properties to Point2D.prototype object as you like. The common pattern is to declare methods to Point2D.prototype and other properties will be declared in the constructor function.

Point2D.prototype称为原型对象p1对象的原型 ,对于使用new Point2D(...)语法创建的任何其他对象,也称为原型对象 。 您可以根据需要向Point2D.prototype对象添加更多属性。 常见的模式是声明Point2D.prototype方法,其他属性将在构造函数中声明。

Built-in objects in JavaScript are constructed in a similar manner. For example:

JavaScript中的内置对象以类似的方式构造。 例如:

  • Prototype of objects created with new Object() or {} syntax is Object.prototype.

    使用new Object(){}语法创建的对象的原型为Object.prototype

  • Prototype of arrays created with new Array() or [] syntax is Array.prototype.

    使用new Array()[]语法创建的数组的原型为Array.prototype

  • And so on with other built-in objects such as Date and RegExp.

    以此类推,以及其他内置对象,例如DateRegExp

Object.prototype is inherited by all objects and it has no prototype (its prototype is null).

Object.prototype被所有对象继承,并且没有原型(原型为null )。

原型链 (Prototype chain)

The prototype chain mechanism is simple: When you access a property p on object obj, the JavaScript engine will search this property inside obj object. If the engine fails to search, it continues searching in the prototype of obj object and so on until reaching Object.prototype. If after the search has finished, and nothing has been found, the result will be undefined. For example:

原型链机制很简单:访问对象obj的属性p时,JavaScript引擎将在obj对象内搜索此属性。 如果引擎搜索失败,它将继续搜索obj对象的原型,依此类推,直到到达Object.prototype 。 如果搜索完成后仍未找到任何内容,则结果将是undefined 。 例如:

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

In above snippet, the statement var obj2 = Object.create(obj1) will create obj2 object with prototype obj1 object. In other words, obj1 becomes the prototype of obj2 instead of Object.prototype by default. As you can see, b is not a property of obj2; you can still access it via the prototype chain. For the c property, however, you get an undefined value because it can’t be found in obj1 and Object.prototype.

在以上代码段中,语句var obj2 = Object.create(obj1)将使用原型obj1对象创建obj2对象。 换句话说,默认情况下, obj1成为obj2的原型,而不是Object.prototype 。 如您所见, b不是obj2的属性; 您仍然可以通过原型链访问它。 但是,对于c属性,您会得到一个undefined值,因为在obj1Object.prototype找不到该Object.prototype

班级 (Classes)

In ES2016, we now get to use the Class keyword as well as the methods mentioned above to manipulate prototype. The JavaScript Class appeals to developers from OOP backgrounds, but it’s essentially doing the same thing as above.

在ES2016中,我们现在可以使用Class关键字以及上述方法来操作prototype 。 JavaScript Class吸引了OOP背景的开发人员,但实际上它的作用与上述相同。

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

This is basically the same as:

这基本上与以下内容相同:

function Rectangle(height, width) {
  this.height = height
  this.width = width
}

Rectangle.prototype.calcArea = function calcArea() {
  return this.height * this.width
}

The getter and setter methods in classes bind an Object property to a function that will be called when that property is looked up. It’s just syntactic sugar to help make it easier to look up or set properties.

类中的gettersetter方法将Object属性绑定到将在查找该属性时调用的函数。 它只是语法糖,可以帮助您更轻松地查找设置属性。

JavaScript作用域示例 (JavaScript Scope Example)

If you’ve been programming in JavaScript for a while, you’ve undoubtedly run into a concept known as scope. What is scope? Why should you take the time to learn it?

如果您使用JavaScript已有一段时间,那么无疑会遇到一个称为scope的概念。 什么是scope ? 您为什么要花时间学习它?

In programmer speak, scope is the current context of execution. Confused? Let’s take a look at the following piece of code:

用程序员来说, 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...

This is a simple example, but it does a good job of illustrating what is known as Lexical scope. JavaScript, and almost every other programming language, has a Lexical scope. There is another kind of scope known as Dynamic scope, but we won’t be discussing that.

这是一个简单的示例,但是在说明所谓的Lexical scope方面做得很好。 JavaScript和几乎所有其他编程语言都具有Lexical范围 。 还有另一种范围称为动态范围 ,但我们不会在此讨论。

Now, the term Lexical scope sounds fancy, but as you will see it’s really simple in principle. In a Lexical Scope, there are two kinds of scopes: the global scope and a local scope.

现在, 词法作用域一词听起来很花哨,但是正如您将看到的,它在原理上真的很简单。 在词法作用域中,有两种作用域: 全局作用域局部作用域

Before you type the first line of code in your program, a global scope is created for you. This contains all the variables that you declare in your program outside any functions.

在程序中键入第一行代码之前,将为您创建一个全局范围 。 它包含您在程序中所有函数之外声明的所有变量。

In the example above, the variable foo is in the global scope of the program, while the variable bar is declared inside a function and is therefore in the local scope of that function.

在上面的示例中,变量foo在程序的全局范围内,而变量bar在函数内部声明,因此在该函数的局部范围内

Let's break down the example line by line. While you might be confused at this point, I promise you will have a much better understanding by the time you finish reading this.

让我们逐行分解示例。 尽管您可能在这一点上感到困惑,但我保证您在阅读完本文后会更好地理解。

On line 1 we are declaring the variable foo. Nothing too fancy here. Let's call this a left-hand size (LHS) reference to foo, because we are assigning a value to foo and it’s on the left-hand side of the equal sign.

在第1行,我们声明了变量foo 。 这里没什么好看的。 我们称其为对foo的左侧大小(LHS)引用,因为我们正在为foo分配一个值,并且它位于equal的左侧。

On line 3, we are declaring a function and assigning it to variable baz. This is another LHS reference to baz. We are assigning a value to it (remember, functions are values too!). This function is then called on line 8. This is a RHS, or a right-hand side reference to baz. We are retrieving baz’s value, which in this case is a function and then invoking it.

在第3行,我们声明一个函数并将其分配给变量baz 。 这是LHS对baz另一种参考。 我们正在为其分配一个值(请记住,函数也是值!)。 然后在第8行调用此函数。这是RHS或baz的右侧引用。 我们正在检索baz的值(在本例中为函数),然后调用它。

Another RHS reference to baz would be if we assigned its value to another variable, for example foo = baz. This would be a LHS reference to foo and a RHS reference to baz.

如果我们将其值分配给另一个变量,例如foo = baz ,则是另一个RHS对baz引用。 这将是对foo的LHS引用和对baz的RHS引用。

The LHS and RHS references might sound confusing, but they are important for discussing scope. Think of it this way: a LHS reference is assigning a value to the variable, while a RHS reference is retrieving the value of the variable. They’re just a shorter and more convenient way of saying ‘retrieving the value’ and ‘assigning a value’.

LHS和RHS参考可能听起来令人困惑,但是它们对于讨论范围很重要。 可以这样考虑:LHS引用正在为变量分配值,而RHS引用正在获取变量的值。 它们只是说“取回价值”和“分配价值”的一种更短,更方便的方式。

Let’s now break down what’s happening inside the function itself.

现在让我们分解一下函数本身内部发生的情况。

When the compiler compiles the code inside a function, it enters the function’s local scope.

当编译器在函数内部编译代码时,它将进入函数的局部作用域

On line 4, the variable bar is declared. This is a LHS reference to bar. On the next line, we have a RHS reference to foo inside the console.log(). Remember, we are retrieving foo’s value and then passing it as an argument to the method console.log().

在第4行,声明了变量bar 。 这是LHS对bar引用。 在下一行,我们在console.log()有一个对foo的RHS引用。 记住,我们正在获取foo的值,然后将其作为参数传递给console.log()方法。

When we have a RHS reference to foo, the compiler looks for the declaration of the variable foo. The compiler doesn’t find it in the function itself, or the function’s local scope, so it goes up one level: to the global scope.

当我们有对foo的RHS引用时,编译器将查找变量foo的声明。 编译器无法在函数本身或函数的本地范围中找到它因此它会向上一级:到全局范围

At this point you’re probably thinking that scope has something to do with variables. That is correct. A scope can be thought of as a container for variables. All variables that are created within a local scope are only accessible in that local scope. However, all local scopes can access the global scope. (I know you’re probably even more confused right now, but just bear with me for a few more paragraphs).

在这一点上,您可能会认为范围与变量有关。 那是正确的。 范围可以视为变量的容器。 在本地范围内创建的所有变量只能在该本地范围内访问。 但是,所有本地范围都可以访问全局范围。 (我知道您现在可能会更加困惑,但是请多忍受几段)。

So the compiler goes up to the global scope to find a LHS reference to the variable foo. It finds one on line 1, so it retrieves the value from the LHS reference, which is a string: 'Hi, I am foo!'. This string is sent to the console.log() method, and outputted to the console.

因此,编译器进入了全局范围,以找到对变量foo的LHS引用。 它在第1行找到一个,因此它从LHS引用中检索值,该值是一个字符串: 'Hi, I am foo!' 。 该字符串发送到console.log()方法,并输出到控制台。

The compiler has finished executing the code inside the function, so we come back out to line 9. On line 9, we have a RHS reference for the variable bar.

编译器已完成函数内部代码的执行,因此我们回到第9行。在第9行,我们为变量bar提供了RHS参考。

Now, bar was declared in the local scope of baz, but there is a RHS reference for bar in the global scope. Since there is no LHS reference for bar in the global scope, the compiler can’t find a value for bar and throws a ReferenceError.

现在,在baz的本地范围内声明了bar ,但是在全局范围内有bar的RHS参考。 由于在全局范围内没有关于bar LHS引用,因此编译器找不到bar的值,并引发ReferenceError。

But, you might ask, if the function can look outside itself for variables, or a local scope can peek into the global scope to find LHS references, why can’t the global scope peek into a local scope? Well that’s how lexical scope works!

但是,您可能会问,如果函数可以在自身之外寻找变量,或者局部范围可以窥视全局范围以查找LHS引用,为什么全局范围不能窥视局部范围? 好吧,这就是词法作用域的工作方式!

... // global scope
var baz = function() {
  ... // baz's scope
}
... /// global scope

This is the same code from above which illustrates the scope. This forms a sort of hierarchy that goes up to the global scope:

这是上面说明范围的相同代码。 这形成了一种上升到全局范围的层次结构:

baz -> global.

baz -> global

So, if there is a RHS reference for a variable inside baz’s scope, it can be fulfilled by a LHS reference for that variable in the global scope. But the opposite is not true.

因此,如果baz范围内有一个变量的RHS引用,则可以通过全局范围内该变量的LHS引用来实现。 但是事实并非如此

What if we had another function inside baz?

如果我们在baz还有另一个功能怎么办?

... // global scope
var baz = function() {
  ... // baz's scope

  var bar = function() {
     ... // bar's scope.
  }

}
... /// global scope

In this case, the hierarchy or the scope chain would look like this:

在这种情况下,层次结构或范围链将如下所示:

bar -> baz -> global

bar -> baz -> global

Any RHS references inside bar’s local scope can be fulfilled by LHS references in the global scope or baz’s scope, but a RHS reference in baz’s scope cannot be fulfilled by a LHS reference in bar’s scope.

任何RHS引用内部bar的局部范围内可以通过LHS引用在全局范围内或满足baz适适用范围“,但在RHS参考baz的范围不能用在LHS参考履行bar适适用范围”。

You can only traverse down a scope chain, not up.

您只能遍历范围链,而不能遍历范围链。

There are other two important things you should know about JavaScript scopes.

您还应该了解JavaScript范围的其他两件事。

  1. Scopes are declared by functions, not by blocks.

    作用域由函数而不是块声明。
  2. Functions can be forward-referenced, variables can’t.

    函数可以被前向引用,变量不能。

Observe (each comment describes scope at the line that it’s written on):

观察(每个注释在其编写的行中描述了范围):

// outer() is in scope here because functions can be forward-referenced
    
    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

JavaScript For循环示例 (JavaScript For Loop Example)

句法 (Syntax)

for ([initialization]); [condition]; [final-expression]) {
   // statement
}

The javascript for statement consists of three expressions and a statement:

javascript for语句包含三个表达式和一个语句:

  • initialization - Run before the first execution on the loop. This expression is commonly used to create counters. Variables created here are scoped to the loop. Once the loop has finished its execution, they are destroyed.

    初始化-在第一次执行循环之前运行。 此表达式通常用于创建计数器。 此处创建的变量的作用域是循环。 一旦循环完成执行,它们将被销毁。
  • condition - Expression that is checked prior to the execution of every iteration. If omitted, this expression evaluates to true. If it evaluates to true, the loop’s statement is executed. If it evaluates to false, the loop stops.

    条件-在每次迭代执行之前检查的表达式。 如果省略,则此表达式的值为true。 如果计算结果为true,则执行循环语句。 如果评估为假,则循环停止。
  • final-expression - Expression that is run after every iteration. Usually used to increment a counter. But it can be used to decrement a counter too.

    final-expression-每次迭代后运行的表达式。 通常用于递增计数器。 但是它也可以用于减少计数器。
  • statement - Code to be repeated in the loop

    语句-在循环中重复的代码

any of these three expressions or the statement can be omitted. For loops are commonly used to count a certain number of iterations to repeat a statement. Use a break statement to exit the loop before the condition expression evaluates to false.

这三个表达式中的任何一个或该语句都可以省略。 For循环通常用于计算一定数量的迭代以重复一条语句。 在条件表达式评估为false之前,使用break语句退出循环。

常见陷阱 (Common Pitfalls)

Exceeding the bounds of an array

超出数组的范围

When indexing over an array many times, it is easy to exceed the bounds of the array (ex. try to reference the 4th element of a 3 element array).

当多次索引数组时,很容易超出数组的范围(例如,尝试引用3元素数组的第4个元素)。

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

There are two ways to fix this code. Set the condition to either i < arr.length or i <= arr.length - 1

有两种方法可以修复此代码。 将条件设置为i < arr.lengthi <= arr.length - 1

例子 (Examples)

Iterate through integers from 0-8

循环访问0到8之间的整数

for (var i = 0; i < 9; i++) {
   console.log(i);
}

output:
0
1
2
3
4
5
6
7
8

Break out of a loop before condition expression is false

在条件表达式为假之前跳出循环

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

JavaScript Break语句示例 (JavaScript Break Statement Example)

The break statement terminates the current loop, switch or label statement and transfers program control to the statement following the terminated statement.

break语句终止当前循环, switchlabel语句,并将程序控制权转移到终止语句之后的语句。

break;

If the break statement is used in a labeled statement, the syntax is as follows:

如果在带标签的语句中使用break语句,则语法如下:

break labelName;

例子 (Examples)

The following function has a break statement that terminates the while loop when i is 3, and then returns the value 3 * x.

以下函数有一个break语句,当i为3时终止while循环,然后返回值3 * x

function testBreak(x) {
  var i = 0;

  while (i < 6) {
    if (i == 3) {
      break;
    }
    i += 1;
  }

  return i * x;
}

In the following example, the counter is set up to count from 1 to 99; however, the break statement terminates the loop after 14 counts.

在下面的示例中,计数器设置为从1到99进行计数。 但是, break语句在14个计数后终止循环。

for (var i = 1; i < 100; i++) {
  if (i == 15) {
    break;
  }
}

JavaScript Do While循环示例 (JavaScript Do While loop example)

The do...while loop is closely related to the while loop. In the do while loop, the condition is checked at the end of the loop.

do...while循环密切相关while循环。 在do while循环中,条件在循环结束时检查。

Here is the syntax for do...while loop:

这是do...while循环的语法

句法: (Syntax:)

do {

   *Statement(s);*

} while (*condition*);

statement(s): A statement that is executed at least once before the condition or Boolean expression is evaluated and is re-executed each time the condition evaluates to true.

语句:在对条件或布尔表达式求值之前至少执行一次的语句,并每次条件求值为true时重新执行。

condition: Here, a condition is a Boolean expression. If the Boolean expression evaluates to true, the statement is executed again. When the Boolean expression evaluates to false, the loops ends.

condition:这里的条件是布尔表达式 。 如果布尔表达式的计算结果为true,则再次执行该语句。 当布尔表达式的计算结果为false时,循环结束。

例: (Example:)

var i = 0;
do {
  i = i + 1;
  console.log(i);
} while (i < 5);

Output:
1
2
3
4
5

JavaScript for In Loop示例 (JavaScript For In Loop Example)

The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

for...in语句以任意顺序遍历对象的可枚举属性。 对于每个不同的属性,可以执行语句。

for (variable in object) {
...
}

Required/OptionalParameterDescriptionRequiredVariable: A different property name is assigned to the variable on each iteration. OptionalObject: an object whose enumerable properties are iterated.

Required / OptionalParameterDescriptionRequiredVariable:每次迭代都为变量分配了不同的属性名称。 OptionalObject:迭代其可枚举属性的对象。

例子 (Examples)

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

JavaScript for Of循环示例 (JavaScript For Of Loop Example)

The for...of statement creates a loop iterating over iterable objects (including Array, Map, Set, Arguments object and so on), invoking a custom iteration hook with statements to be executed for the value of each distinct property.

for...of语句创建一个循环,循环访问可迭代对象(包括Array,Map,Set,Arguments对象等),并为每个不同属性的值调用要执行的语句的自定义迭代挂钩。

for (variable of object) {
        statement
    }

Description variable: On each iteration a value of a different property is assigned to the variable.object Object whose enumerable properties are iterated.

描述变量:在每次迭代中,将不同属性的值分配给variable.object迭代其可枚举属性的对象。

例子 (Examples)

数组 (Array)

let arr = [ "fred", "tom", "bob" ];

    for (let i of arr) {
        console.log(i);
    }

    // Output:
    // fred
    // tom
    // bob

地图 (Map)

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

(Set)

var s = new Set();
    s.add(1);
    s.add("red");

    for (var n of s) {
        console.log(n);
    }

    // Output:
    // 1
    // red

参数对象 (Arguments object)

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

JavaScript While循环示例 (JavaScript While Loop Example)

The while loop starts by evaluating the condition. If the condition is true, the statement(s) is/are executed. If the condition is false, the statement(s) is/are not executed. After that, while loop ends.

while循环通过评估条件开始。 如果条件为真,则执行该语句。 如果条件为假,则不执行该语句。 之后,while循环结束。

Here is the syntax for the while loop:

这是while循环的语法

句法: (Syntax:)

while (condition)

{

  statement(s);

}

statement(s): A statement that is executed as long as the condition evaluates to true.

statement(s):只要条件评估为真,就执行该语句。

condition: Here, the condition is a Boolean expression which is evaluated before each pass through the loop. If this condition evaluates to true, statement(s) is/are executed. When the condition evaluates to false, execution continues with the statement after the while loop.

condition:这里的条件是布尔表达式,在每次通过循环之前都会对其求值。 如果此条件的值为真,则执行语句。 当条件评估为false时,将在while循环之后继续执行该语句。

例: (Example:)

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

翻译自: https://www.freecodecamp.org/news/javascript-example/

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/cumian8165/article/details/108153402

智能推荐

FPGA 基于双端口RAM的串口通信系统_fpga双口sram通信-程序员宅基地

文章浏览阅读1.4k次。FPGA实验报告文章目录一、概述1、目的及意义:2、主要功能:二、原理及步骤1、原理框图:2、工作原理3、功能模块简介4、实验步骤三、程序设计及描述四、仿真与综合测试五、总结一、概述1、目的及意义:设计居于双端口RAM的串口的通信系统。实现用COMPORT发送数据,并在FPGA上用七段数码管显示出来。2、主要功能:FIFO队列是一种数据缓冲器,用于数据的缓存。他是一种先入先出的存储器,即最先写入的数据,最先读。FIFO的参数有数据深度和数据宽度。数据宽度是指存储数据的宽度。深度是指存储器可_fpga双口sram通信

神经网络(vanilla ver.) in numpy_vanillaw神经网络 python-程序员宅基地

文章浏览阅读2k次。写在最前vanilla neural network 学习材料有好多 前年年都是用MATLAB写的,写的还挺丑,后来用tensorflow写把底层细节都盖住了。 这里是一个只用numpy实现的版本学习材料的话。MATLAB推荐王小川的 45个神经网络案例 第一章 数学推导推荐吴恩达的Ufldl 反向传导算法细节activation function 的求导比较有技巧sigmoid : 1_vanillaw神经网络 python

人脸对齐--Face Alignment In-the-Wild: A Survey_人脸对齐 综述-程序员宅基地

文章浏览阅读8.2k次。Face Alignment In-the-Wild: A Survey Computer Vision and Image Understanding Volume 162, September 2017, Pages 1-22 https://www.sciencedirect.com/science/article/pii/S1077314217301455人脸对齐综述文献人脸对齐的定_人脸对齐 综述

模板——并差集_力扣和acm-程序员宅基地

文章浏览阅读106次。并差集_ACM模板题目描述第1行给出两个正整数,分别是城镇数目N (N < 1000 )和道路数目M。随后的M行对应M条道路,每行给出一对正整数,分别是该条道路直接连通的两个城镇的编号。为简单起见,城镇从1到N编号。要使任何两个城镇间都可以实现交通,但不一定有直接的道路相连,只要互相间接通过道路可达即可,输出最少还需要建设的道路数目?const int maxn = 1010;//N..._力扣和acm

分层强化学习 学习笔记-程序员宅基地

文章浏览阅读1.5k次,点赞5次,收藏25次。MLSH的idea很自然,简单有效,temporal abstraction的做法和common 的 HRL方法基本一致需要注意的一点是,通常single task中,为了training的稳定性,会keep master policy random,warmup subpolicy,这是希望master policy能在subpolicy有一定level之后,再进行有效learning;_分层强化学习

山东中职计算机应用基础课件,计算机应用基础课件(中职)-精选版.ppt-程序员宅基地

文章浏览阅读318次。计算机应用基础课件(中职)-精选版.ppt计算机应用基础 目录 第一章 计算机基础知识 1.1 计算机的定义 计算机又称“电脑”。 电子计算机是一种可以输入、输出、处理、存储数据和 信息,无需人类干预的一类电子设备。 1.2 计算机的发展历程 ? 1946年2月14日,世界上第一台电脑ENIAC在美国 ...

随便推点

Docker的ARG、ENV和.env配置完整指南_docker env-程序员宅基地

文章浏览阅读1.7w次,点赞5次,收藏14次。本文将帮助您自信地使用 Docker ARG、ENV、env_file 和 .env 文件。您将了解如何使用 Docker 构建时变量、环境变量和 docker-compose 模板轻松配置 Docker 映像和 dockerized 应用程序。常见的误解.env 文件仅在使用docker-compose.yml 文件时的预处理步骤中使用。美元符号变量(如 $HI)被替换为同一目录中名为“.env”的文件中包含的值。ARG仅在构建 Docker 映像(RUN ..._docker env

数的三次方根 JAVA解法_java如何表示三次根-程序员宅基地

文章浏览阅读3.4k次。给定一个浮点数n,求它的三次方根。输入格式共一行,包含一个浮点数n。输出格式共一行,包含一个浮点数,表示问题的解。注意,结果保留6位小数。数据范围−10000≤n≤10000−10000≤n≤10000输入样例:1000.00输出样例:10.000000import java.util.*;public class Main{ pu..._java如何表示三次根

汇编语言——学习资料(更新........)-程序员宅基地

文章浏览阅读1.4k次,点赞3次,收藏12次。知乎引用“ 学汇编不是说一定要用这玩艺做多牛鼻的事情, 问题的关键在于, 学透了汇编会使你真正理解计算机另外一方面, 如上面所说, 在工作中你迟早会在某个阴暗的角落遇到汇编. 不管你承认不承认, 现在的CPU没有直接跑高级语言的, 哪怕是虚拟机也都是类似汇编的指令集.当遇到崩溃分析, 性能优化甚至编译器抽风等等的时候, 汇编是你最后一根救命稻草.”作者:Skogkatt 链接:https://w

经典算法之递归(Recursion)_recursion算法编程-程序员宅基地

文章浏览阅读6.5k次,点赞5次,收藏28次。1、递归的定义  递归:你打开面前这扇门,看到屋里面还有一扇门(这门可能跟前面打开的门一样大小(静),也可能门小了些(动)),你走过去,发现手中的钥匙还可以打开它,你推开门,发现里面还有一扇门,你继续打开,。。。, 若干次之后,你打开面前一扇门,发现只有一间屋子,没有门了。 你开始原路返回,每走回一间屋子,你数一次,走到入口的时候,你可以回答出你到底用这钥匙开了几扇门。  循环:你打开面前..._recursion算法编程

Visio2016通过部署工具的方式进行安装_已有visio安装包怎么用部署工具安装-程序员宅基地

文章浏览阅读1.5k次。由于我电脑是Office2016的版本,我下载好visio2016后,解压到文件夹。由于之前安装的是即点即用的office,所以出现了以下问题:后来在网上查到可以使用部署工具进行安装,点击一下网站进行下载office部署工具:https://www.microsoft.com/en-us/download/details.aspx?id=491171.首先下载好部署工具,解压该工具到visio中setup.exe文件夹中2.运行该工具,选择visio中setup.exe文件夹生成相应的c_已有visio安装包怎么用部署工具安装

【沙发管家】电视猫3.1.6新版体验:资源更全面,院线大片看到爽!-程序员宅基地

文章浏览阅读160次。近日电视猫迎来了最新版本(V3.1.6)的更新,此次更新除了新增的奇趣频道,优化了智能推荐算法,最大的亮点,应该就是新推出的影视VIP服务了,新版极大地扩展了内容包(电影、电视剧、综艺、少儿、海外剧、纪录片),资源更全面。下面我们就一起体验一番最新版电视猫的不同之处吧。近日电视猫迎来了最新版本(V3.1.6)的更新,此次更新除了新增的奇趣频道,优化了智能推荐算法,最大的亮点,应该就是新推出的影..._电视猫3.1.6

推荐文章

热门文章

相关标签