Javascript 简明教程

JavaScript - ES5

JavaScript ES5 ,也称为 ECMAScript 5,于 2009 年发布。它是 JavaScript 的首次重大修订。它引入了许多新功能,包括 getterssetters ,以及“ use strict ”指令。ES5 已经比以前的 JavaScript 版本有了显著的改进。ES5 中引入的新功能使代码更强大、更简洁,更易于维护。

JavaScript ES5, also known as ECMAScript 5, was released in 2009. It was the first major revision of JavaScript. It introduced many new features, including getters and setters, and 'use strict' directive. ES5 has provided significant improvement over the previous versions of JavaScript. The new features introduced in ES5 make code more powerful, concise and easier to maintain.

New Added Features in JavaScript ES5

以下是 JavaScript ES5 版本中添加的新方法、功能等。

Here are the new methods, features, etc., added to the ES5 version of JavaScript.

  1. Array every()

  2. Array filter()

  3. Array forEach()

  4. Array isArray()

  5. Array indexOf()

  6. Array lastIndexOf()

  7. Array map()

  8. Array reduce()

  9. Array reduceRight()

  10. Array some()

  11. Date now()

  12. Date toJSON()

  13. Date toISOString()

  14. Function bind()

  15. JSON parse()

  16. JSON stringify()

  17. Multiline strings

  18. Object methods

  19. Object defineProperty()

  20. Property getters and setters

  21. Reserved words as property names

  22. "use strict"

  23. String[number] access

  24. String trim()

  25. Trailing commas

这里,我们详细解释了每项特性。

Here, we have explained each feature in detail.

JavaScript Array every()

array.every() 方法检查数组的每个元素是否遵循特定条件。

The array.every() method checks whether each element of the array follows a particular condition.

Example

在下面的代码中,我们使用 array.every() 方法来检查数组的每个元素是否是偶数。

In the below code, we use the array.every() method to check whether each element of the array is even.

<html>
<body>
   <div id = "output"> All elements of the array are even? </div>
   <script>
      const arr = [10, 20, 30, 40, 2, 6];
      function even(element) {
         return element % 2 == 0;
      }
      document.getElementById("output").innerHTML += arr.every(even);
   </script>
</body>
</html>
All elements of the array are even? true

JavaScript Array filter()

array.filter() 过滤数组元素并在新数组中获取过滤元素。

The array.filter() filters array elements and gets filtered elements in the new array.

Example

在下面的代码中,我们过滤可被 10 整除的数组元素。

In the below code, we filter the array elements which are divisible by 10.

<html>
<body>
   <div id = "output"> Elements divisible by 10 are </div>
   <script>
      const arr = [10, 20, 8, 30, 40, 2, 6];
      function divide(element) {
         return element % 10 == 0;
      }
      document.getElementById("output").innerHTML +=  arr.filter(divide);
   </script>
</body>
</html>
Elements divisible by 10 are 10,20,30,40

JavaScript Array forEach()

array.forEach() 遍历数组元素。它类似于 JavaScript 中的循环。

The array.forEach() traverses the array elements. It is similar to loops in JavaScript.

Example

下面的代码使用 array.forEach() 方法遍历数组并在新行中打印每个数组元素。

The below code uses the array.forEach() method to traverse the array and print each array element in the new line.

<html>
<body>
   <div id="output"> </div>
   <script>
      const arr = ["TATA", "Honda", "Toyota", "Maruti"];
      arr.forEach(traverse); // Using the array.forEach() method
      function traverse(element) {
         document.getElementById("output").innerHTML += element + "<br>";
      }
   </script>
</body>
</html>
TATA
Honda
Toyota
Maruti

JavaScript Array isArray()

Array.isArray() 方法检查作为参数传递的对象是否是一个数组。

The Array.isArray() method checks whether the object passed as an argument is an array.

Example

下面的代码使用 Array.isArray() 方法检查 arr 是否是一个数组。

The below code checks whether the arr is an array using the Array.isArray() method.

<html>
<body>
   <div id = "output"> </div>
   <script>
      const arr = ["TATA", "Honda", "Toyota", "Maruti"];
      let bool = Array.isArray(arr);
      document.getElementById("output").innerHTML += "Is arr array? " + bool;
   </script>
</body>
</html>
Is arr array? true

JavaScript Array indexOf()

array.indexOf() 方法返回数组中特定元素的第一个索引。

The array.indexOf() method returns the first index of the particular element in the array.

Example

下面的代码在 arr 中查找第一个 23 的索引,即 0。

The below code finds the first index of 23 in the array, which is 0.

<html>
<body>
   <div id = "output"> The first index of 23 in the array is </div>
   <script>
      const arr = [23, 45, 32, 12, 23, 56];
      document.getElementById("output").innerHTML += arr.indexOf(23);
   </script>
</body>
</html>
The first index of 23 in the array is 0

JavaScript Array lastIndexOf()

array.lastIndexOf() 方法返回数组中特定元素的最后一个索引。

The array.lastIndexOf() method returns the last index of the particular element in the array.

Example

下面的代码查找 arr 中 45 的最后一个索引,即 4。

The code below finds the last index of the 45 in the array, which is 4.

<html>
<body>
   <div id = "output"> The last index of 45 in the array is </div>
   <script>
      const arr = [23, 45, 32, 45, 45, 56];
      document.getElementById("output").innerHTML += arr.lastIndexOf(45);
   </script>
</body>
</html>
The last index of 45 in the array is 4

JavaScript Array map()

array.map() 方法返回一个新的数组,其中映射了当前的数组元素与新的数组元素。

The array.map() method returns a new array after mapping current array elements with new ones.

Example

下面的代码使用 map() 方法创建一个新数组,该数组中的元素是原数组元素的两倍。

The below code uses the map() method to create a new array by doubling the array elements.

<html>
<body>
   <div id = "output"> The new array is </div>
   <script>
      const arr = [1, 2, 3, 4, 5];
      function doubleEle(element) {
         return element * 2;
      }
      document.getElementById("output").innerHTML += arr.map(doubleEle);
   </script>
</body>
</html>
The new array is 2,4,6,8,10

JavaScript Array reduce()

array.reduce() 方法将数组简化为一个值。

The array.reduce() method reduces the array to a single value.

Example

下面的代码使用 array.reduce() 方法将数组所有元素相乘。

The below code multiples all elements of the array using the array.reduce() method.

<html>
<body>
   <div id = "output">The multiplication result of the array elements is </div>
   <script>
      const arr = [1, 2, 3, 4, 5];
      function multiplier(multiplication, element) {
         return multiplication * 2;
      }
      document.getElementById("output").innerHTML += arr.reduce(multiplier);
   </script>
</body>
</html>
The multiplication result of the array elements is 16

JavaScript Array reduceRight()

array.reduceRight() 方法不是从左到右,而是从右到左简化数组。

The array.reduceRight() method reduces the array from right to left instead of left to right.

Example

<html>
<body>
   <div id = "output">The merged array elements in the reverse order is: </div>
   <script>
      const arr = ["How", "are", "you", "doing?"];
      function merge(res, element) {
         return res += element + " ";
      }
      document.getElementById("output").innerHTML += arr.reduceRight(merge);
   </script>
</body>
</html>
The merged array elements in the reverse order is: doing?you are How

JavaScript Array some()

array.some() 方法用于检查数组中是否有一些元素遵循特定条件。

The array.some() method is used to check whether some elements of the array follow the particular condition.

Example

下面的代码检查数组是否包含一个或多个长度大于 3 的字符串。

The code below checks whether the array contains 1 or more strings with lengths greater than 3.

<html>
<body>
   <div id = "output">Array contains one or more strings with lengths greater than 3?  </div>
   <script>
      const arr = ["How", "are", "you", "doing?"];
      function func_len(element) {
         return element.length > 3;
      }
      document.getElementById("output").innerHTML += arr.some(func_len);
   </script>
</body>
</html>
Array contains one or more strings with lengths greater than 3? true

JavaScript Date now()

Date.now() 方法用于获取自 1970 年 1 月 1 日以来的总毫秒数。

The Date.now() method is used to get the total number of milliseconds since 1st January 1970.

Example

下面的代码查找从 1970 年 1 月 1 日以来的总毫秒数。

The below code finds the total milliseconds from 1st January 1970.

<html>
<body>
   <div id = "output">Total milliseconds since 1st January, 1970 is: </div>
   <script>
      document.getElementById("output").innerHTML += Date.now();
   </script>
</body>
</html>
Total milliseconds since 1st January, 1970 is: 1702540225136

JavaScript Date toJSON()

date.toJSON() 方法将日期转换为 JSON 日期格式。JSON 日期格式与 ISO 格式相同。ISO 格式为 YYYY-MM-DDTHH:mm:ss.sssZ。

The date.toJSON() method converts the date into the JSON date format. The JSON date format is the same as the ISO format. The ISO format is YYYY-MM-DDTHH:mm:ss.sssZ.

Example

下面的代码以 JSON 格式打印当前日期。

The below code prints the current date in JSON format.

<html>
<body>
   <div id = "output">The current date in JSON format is: </div>
   <script>
      const date = new Date();
      document.getElementById("output").innerHTML += date.toJSON();
   </script>
</body>
</html>
The current date in JSON format is: 2023-12-18T06:12:52.366Z

JavaScript Date toISOString()

date.toISOString() 方法用于将日期转换为 ISO 标准格式。

The date.toISOString() method is used to convert the date into the ISO standard format.

Example

下面的代码以标准 ISO 字符串格式打印当前日期。

The below code prints the current date in the standard ISO string format.

<html>
<body>
   <div id = "output">The current date in ISO string format is: </div>
   <script>
      const date = new Date();
      document.getElementById("output").innerHTML += date.toISOString();
   </script>
</body>
</html>
The current date in ISO string format is: 2023-12-18T06:13:50.159Z

JavaScript Function bind()

bind() 方法用于从另一个对象借用方法。

The bind() method is used to borrow the method from another object.

Example

以下代码中,bird 对象包含 printInfo() 方法和属性。animal 对象仅包含 name 和 category 属性。

In the below code, the bird object contains the properties and printInfo() method. The animal object contains only name and category properties.

我们使用 bind() 方法为 animal 对象从 bird 对象借用 printInfo() 方法。在输出中,printInfo() 方法打印 animal 对象的信息。

We used the bind() method to borrow the printInfo() method from the bird object for the animal object. In the output, the printInfo() method prints the information of the animal object.

<html>
<body>
   <div id = "result"> </div>
   <script>
      const output = document.getElementById("result");
      const bird = {
         name: "Parrot",
         category: "Bird",
         printInfo() {
            return "The name of the " + this.category + " is - " + this.name;
         }
      }

      const animal = {
         name: "Lion",
         category: "Animal",
      }
      const animalInfo = bird.printInfo.bind(animal);
      output.innerHTML += animalInfo();
   </script>
</body>
</html>
The name of the Animal is - Lion

JavaScript JSON parse()

JSON.parse() 方法用于将字符串转换为 JSON 对象。

The JSON.parse() method is used to convert the string into the JSON object.

Example

下面给出的代码将字符串转换为对象。此外,我们还在输出中打印了对象属性的值。

The code given below converts the string into an object. Also, we have printed the values of object properties in the output.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      const objStr = '{"name":"Sam", "age":40, "city":"Delhi"}';
      const obj = JSON.parse(objStr);
      output.innerHTML += "The parsed JSON object values are - <br>";
      output.innerHTML += "name : " + obj.name + "<br>";
      output.innerHTML += "age : " + obj.age + "<br>";
      output.innerHTML += "city: " + obj.city + "<br>";
   </script>
</body>
</html>
The parsed JSON object values are -
name : Sam
age : 40
city: Delhi

JavaScript JSON stringify()

JSON.stringify() 方法将对象转换为字符串。

The JSON.stringify() method converts the object into a string.

Example

下面的代码使用 JSON.stringify() 方法将 obj 对象转换为字符串。

The code below converts the obj object into the string using JSON.strringify() method.

<html>
<body>
   <div id = "output">The object in the string format is - </div>
   <script>
      const obj = {
         message: "Hello World!",
         messageType: "Welcome!",
      }
      document.getElementById("output").innerHTML += JSON.stringify(obj);
   </script>
</body>
</html>
The object in the string format is - {"message":"Hello World!","messageType":"Welcome!"}

JavaScript Multiline Strings

可以使用反斜杠('\')来换行字符串并在多行中定义字符串。

You can use the backslash (‘\’) to break the line of the string and define the string in multiline.

Example

在下面的示例中,我们已经将 'str' 字符串定义在多行中,并使用反斜杠进行换行。

In the below example, we have defined the ‘str’ string in multiple lines and used the backslash to break the line.

<html>
<body>
   <div id = "output"> </div>
   <script>
      let str = "Hi \
                 user";
      document.getElementById("output").innerHTML += "The string is - " + str;
   </script>
</body>
</html>
The string is - Hi user

JavaScript Object Methods

在 ES5 中,对象相关的方法被添加进来,用于操作和保护对象。

In ES5, object-related methods are added to manipulate and protect the objects.

Methods to Manipulate the Object

Sr.No.

Method

Description

1

create()

To creat a new object, using an existing object as the prototype.

2

defineProperty()

To make a clone of the object and add new properties to its prototype.

3

defineProperties()

To define a property into a particular object and get the updated object.

4

getOwnPropertyDescriptor()

To get the property descriptor for the properties of the object.

5

getOwnPropertyNames()

To get object properties.

6

getPrototypeOf()

To get the prototype of the object.

7

keys()

To get all keys of the object in the array format.

Methods to Protect the Object

Sr.No.

Method

Description

1

freeze()

To prevent adding or updating object properties by freezing the object.

2

seal()

To seal the object.

3

isFrozen()

To check if the object is frozen.

4

isSealed()

To check if the object is sealed.

5

isExtensible()

To check if an object is extensible.

6

keys()

To get all keys of the object in the array format.

7

preventExtensions()

To prevent the prototype updation of the object.

JavaScript Object defineProperty()

可以使用 Object.defineProperty() 方法来定义对象的单个属性,或更新属性值和元数据。

You can use the Object.definedProperty() method to define a single property of the object or update the property value and metadata.

Example

下面代码包含汽车对象的品牌、车型和价格属性。我们使用 defineProperty() 方法来定义对象中的 gears 属性。

The code below contains the car object’s brand, model, and price properties. We used the defineProperty() method to define the ‘gears’ property in the object.

<html>
<body>
   <div id = "output">The obj object is - </div>
   <script>
      const car = {
         brand: "Tata",
         model: "Nexon",
         price: 1000000,
      }
      Object.defineProperty(car, "gears", {
         value: 6,
         writable: true,
         enumerable: true,
         configurable: true
      })

      document.getElementById("output").innerHTML += JSON.stringify(car);
   </script>
</body>
</html>
The obj object is - {"brand":"Tata","model":"Nexon","price":1000000,"gears":6}

JavaScript Property getters and setters

getters 和 setters 用于安全地访问和更新对象属性。

The getters and setters are used to access and update the object properties securely.

Example

在下面的代码中,watch 对象包含品牌和表盘属性。我们已经使用 get 关键字定义了 getter 来访问品牌属性值。

In the below code, the watch object contains the brand and dial properties. We have defined the getter using the get keyword to access the brand property value.

此外,我们还使用 set 关键字定义了 setter,以将表盘属性值设定为大写。

Also, we have defined the setter using the set keyword to set the dial property value in the upper case.

通过这种方式,可以保护更新后的对象属性值。

In this way, you can secure the updating object property value.

<html>
<body>
   <div id = "demo"> </div>
   <script>
      const output = document.getElementById("demo");
      const watch = {
         brand: "Titan",
         dial: "ROUND",
         // Getter to get brand property
         get watchBrand() {
            return this.brand;
         },
         // Setter to set Watch dial
         set watchDial(dial) {
            this.dial = dial.toUpperCase();
         }
      }
      output.innerHTML = "The Watch brand is - " + watch.watchBrand + "<br>";
      watch.watchDial = "square";
      output.innerHTML += "The Watch dial is - " + watch.dial;
   </script>
</body>
</html>
The Watch brand is - Titan
The Watch dial is - SQUARE

JavaScript Reserved words as property names

在 ES5 之后,可以使用反向单词作为对象中的属性名。

After ES5, you can use the reversed words as a property name in the object.

Example

在下面的代码中,'delete' 被用作对象属性名。

In the below code, ‘delete’ is used as an object property name.

<html>
<body>
   <div id = "output">The obj object is - </div>
   <script>
      const obj = {
         name: "Babo",
         delete: "Yes",
      }
      document.getElementById("output").innerHTML += JSON.stringify(obj);
   </script>
</body>
</html>
The obj object is - {"name":"Babo","delete":"Yes"}

JavaScript "use strict"

ES5 还引入了严格模式。

The strict mode was also introduced in the ES5.

严格模式允许你克服错误并编写清晰的代码。你可以使用“use strict”指令来声明严格模式。

The strict mode allows you to overcome errors and write clear code. You can use the ‘use strict’ directive to declare the strict mode.

Example

在下面的代码中,你可以取消对“num = 43”行的注释并观察该错误。严格模式不允许开发者在不使用 var、let 或 const 关键字的情况下定义变量。

In the below code, you can uncomment the ‘num = 43’ line and observe the error. The strict mode doesn’t allow developers to define the variables without using var, let, or const keywords.

<html>
<body>
   <div id = "output">The value of num is: </div>
   <script>
      "use strict";
      let num = 43; // This is valid
      // num = 43; // This is invalid
      document.getElementById("output").innerHTML += num + "<br>";
   </script>
</body>
</html>
The value of num is: 43

JavaScript String[number] access

在 ES5 之前,charAt() 方法被用于从特定索引访问字符串字符。

Before ES5, the charAt() method was used to access the string character from a particular index.

在 ES5 之后,你可以将字符串视为一个字符数组,并像访问数组元素一样从特定索引访问字符串字符。

After ES5, you can consider the string as an array of characters and access string characters from the specific index as you access array elements.

Example

<html>
<body>
   <div id = "output1">The first character in the string is: </div>
   <div id = "output2">The third character in the string is: </div>

   <script>
      let str = "Apple";
      document.getElementById("output1").innerHTML += str[0];
      document.getElementById("output2").innerHTML += str[2];
   </script>
</body>
</html>
The first character in the string is: A
The third character in the string is: p

JavaScript String trim()

string.trim() 方法删除了两端的空格。

The string.trim() method removes the whitespaces from both ends.

Example

在下面的代码中,我们使用 string.trim() 方法从 str 字符串的起始和结束位置删除了空格。

In the below code, we used the string.trim() method to remove the whitespaces from the start and end of the str string.

<html>
<body>
   <div id = "output"> </div>
   <script>
      let str = "    Hi, I am a string.    ";
      document.getElementById("output").innerHTML = str.trim();
   </script>
</body>
</html>
Hi, I am a string.

JavaScript Trailing commas

你可以在数组和对象中添加尾部逗号(在最后一个元素后面加逗号)。

You can add a trailing comma (A comma after the last element) in the array and object.

Example

在下面的代码中,我们在最后一个对象属性和数组元素之后添加了尾部逗号。该代码在没有错误的情况下运行并打印输出。

In the below code, we have added the trailing comma after the last object property and array element. The code runs without error and prints the output.

<html>
<body>
   <div id = "demo1"> </div>
   <div id = "demo2"> </div>
   <script>
      const obj = {
         name: "Pinku",
         profession: "Student",
      }
      document.getElementById("demo1").innerHTML =JSON.stringify(obj);
      let strs = ["Hello", "world!",];
      document.getElementById("demo2").innerHTML = strs;
   </script>
</body>
</html>
{"name":"John","profession":"Student"}
Hello,world!

注意 - JSON 字符串不允许尾部逗号。

Note – The JSON string doesn’t allow the trailing comma.

例如,

For example,

let numbers = '{"num1": 10,"num2": 20,}';
JSON.parse(numbers); // Invalid

numbers ='{"num1": 10,"num2": 20}';
JSON.parse(numbers); // Valid

在 ES5 中,主要是引入了数组和对象相关的方法。

In ES5, mostly array and object-related methods are introduced.