Some super useful features in JavaScript over the past five years!
Technology is always evolving, and JavaScript has undergone a lot of changes since its inception in 1995. It has added many new features since then. This article discusses some of the super useful (but probably lesser-known) features that have been added to JavaScript in the last 5 years! But it doesn't cover all features.
String.padStart() and String.padEnd()
The two string methods fill the string into Quick and easy method for other strings. As the name suggests, String.padStart()
adds a new string to the beginning of the given string, and String.padEnd()
appends a string to the beginning of the given string. end.
Note: These methods do not change the original string.
String.padStart(desiredStringLength, stringToAdd)
- desiredStringLength: The length of the number you want the new string to be. [Recommended learning: javascript video tutorial]
- stringToAdd: This is the string to be added to the beginning of the original string.
Let's look at an example:
Code example:
//最初的字符串 let originalString = 'Script'; //对原始的字符串添加字符串 let paddedString = originalString.padStart(10, 'Java'); console.log(paddedString); // 输出 --> // 'JavaScript'
If "we want the new string length" shorter than "the length of the original string to be added". What happens?
In this case, we add
to the string that will be added to the beginning of the original string
The excess part will be truncated.
Example:
let originalString = 'Script'; let paddedString = originalString.padStart(7, 'Java'); console.log(paddedString); // 输出 --> // 'JScript' // 把将要添加到原始字符串开头的字符串从“Java”截断为“J”
If we want the length of the new string to be longer than ' the length of the original string the string to be added "What should I do if 长?
This may cause the results not to meet our expectations! It will
repeate
the string that will be added to the beginning of the original string until it equals our desired length of the new string
Code example:
let originalString = 'Script'; let paddedString = originalString.padStart( 15, 'Java'); console.log(paddedString); // 输出 --> // 'JavaJavaJScript'
It will add spacesin front of the
of the
original string until the string length equals our desired new string length
Code example:
let originalString = 'Script'; let paddedString = originalString.padStart(15); console.log(paddedString); // 输出 --> // " Script"
It will return acopy
of the original string intact:
Code example:
let originalString = 'Script'; let paddedString = originalString.padStart('Java'); console.log(paddedString); // 输出 --> // 'Script'
String.padEnd(desiredStringLength, stringToAppend)
- desiredStringLength: The length of the number you want the new string to be.
- stringToAdd: This is the string to be added to the beginning of the original string.
String.padStart() but appends the string to the end of the given string.
Code example:
let originalString = 'Web'; let paddedString = originalString.padEnd(6, 'Dev'); console.log(paddedString); // 输出 --> // 'WebDev
- desiredStringLength < Raw string stringToAppend? stringToAppend appended to the end of the original string will be truncated.
- desiredStringLength > original string stringToAppend? stringToAppend that repeatedly appends to the end of the original string until desiredStringLength is reached.
- No stringToAppend parameter passed? Spaces will be appended to the original string until desiredStringLength is reached.
- No desiredStringLength parameter passed? A copy of the original string will be returned unchanged.
String.replaceAll(pattern, replacement)
- pattern: The string we are going to replace
- replacement: The string we want to replace
String.replace() before, it accepts a pattern parameter and a replacement parameter, and replaces the first occurrence of the matching pattern in the string. The pattern parameter can be a
string or a
RegEx.
String.replaceAll() is more powerful, as the name suggests, it allows us to replace all occurrences of the specified pattern with the replacement string, not just the first occurrence.
Code examples:
// 使用示例 String.replace() const aString = 'My name is z. z is my name.'; const replaceString = aString.replace('z', 'zayyo'); console.log(replaceString); // 输出 --> // "My name is zayyo. z is my name." // 仅仅吧第一个“z”被替换为“zayyo” // 使用示例 String.replaceAll() with regex const regex = /z/ig; const anotherString = 'My name is z. z is my name.'; const replaceAllString = anotherString.replaceAll(regex, 'zayyo'); console.log(replaceAllString); // 输出 --> // ""My name is zayyo. zayyo is my name."." // 把所有的z都替换成zayyo了
Object.entries(), Object.keys(), Object.values() and Object.fromEntries()
The above methods are useful for converting some data structures. .Object.entries(originalObject)
此对象方法接收一个对象并返回一个新的二维数组,每个嵌套数组都包含原始对象的键和值作为元素。
代码示例:
const fruitObject = { 'banana': 'yellow', 'strawberry': 'red', 'tangerine': 'orange' }; const fruitArray = Object.entries(fruitObject); console.log(fruitArray); // 输出 --> // [["banana", "yellow"], ["strawberry", "red"], ["tangerine", "orange"]]
在转换我们的数据时,这是一种超级好用的方法。下面这个示例是访问对象中的特定键值对的用法:
代码示例:
const fruitObject = { 'banana': 'yellow', 'strawberry': 'red', 'tangerine': 'orange' }; const firstFruit = Object.entries(fruitObject)[0]; console.log(firstFruit); // 输出 --> // ['banana', 'yellow']
在JavaScript 中的很多东西都是对象的形式保存的。因此,我们还可以将数组和字符串作为参数传入给Object.entries()
它们会强制把数组和字符串转换为对象。
代码示例:
const string = 'Hello' const stringAsArgument = Object.entries(string); console.log(stringAsArgument); // 输出 --> // [["0", "H"], ["1", "e"], ["2", "l"], ["3", "l"], ["4", "o"]]
字符串中的每个字符都被插入到一个单独的数组中,并将其索引设置为数组的第一个元素。当您将数组作为参数传递时,也会发生一样的操作:
const array = [1,2,3] const formattedArray = Object.entries(array);console.log(formattedArray);// 输出 --> // [["0", 1], ["1", 2], ["2", 3]]复制代码
注意: 对于这两种情况,第一个元素(索引)都是一个字符串。
Object.keys(anObject)
Object.keys
方法接受一个对象作为参数,并且返回一个以对象的键作为元素的数组。
代码示例:
const programmingLangs = { 'JavaScript': 'Brendan Eich', 'C': 'Dennis Ritchie', 'Python': 'Guido van Rossum' }; const langs = Object.keys(programmingLangs); console.log(langs); // 输出 --> // ["JavaScript", "C", "Python"]
如果我们尝试传递一个字符串作为参数呢?会是什么结果呢?
代码示例:
const string = 'Hallo'; const stringArray = Object.keys(string); console.log(stringArray); // 输出 --> // ["0", "1", "2", "3", "4"]
在这种情况下,字符串也会被强制转换为一个对象。每个字母代表值,它的索引代表键,所以我们返回的数组,就变成了包含字符串中每个字母的索引。
Object.values(anObject)
Object.values()
方法的功能和我们刚刚学习的方法类似,但它不是返回数组中的对象键,而是返回数组中的对象值。
代码示例:
const programmingLangs = { 'JavaScript': 'Brendan Eich', 'C': 'Dennis Ritchie', 'Python': 'Guido van Rossum' }; const creators = Object.values(programmingLangs); console.log(creators); // 输出 --> // ["Brendan Eich", "Dennis Ritchie", "Guido van Rossum"]
Object.entries()
和我们在之前学习Object.keys()
一样,我们也可以传入其他数据类型,例如字符串。
代码示例:
const string = 'Bonjour' const stringArray = Object.values(string); console.log(stringArray) // 输出 --> // ["B", "o", "n", "j", "o", "u", "r"]
Object.fromEntries(anIterable)
Object.fromEntries()
与Object.entries()
相反。它接受一个可迭代对象作为参数,例如数组或映射,并返回一个对象。让我们来看看:
代码示例:
const arrayTranslations = [ ['french', 'bonjour'], ['spanish', 'buenos dias'], ['czech', 'dobry den'] ]; const objectTranslations = Object.fromEntries(arrayTranslations); console.log(objectTranslations); // 输出 --> /*Object { french: "bonjour", spanish: "buenos dias", czech: "dobry den" }*/
因此,我们的可迭代对象(在示例中的嵌套数组)被迭代,并且每个子数组都转换为一个对象,其中索引 0 处的元素作为键,索引 1 处的元素作为值。
因为内容太多后续会继续补全,也欢迎大家在评论区补充..
更多编程相关知识,请访问:编程教学!!
The above is the detailed content of Some super useful features in JavaScript over the past five years!. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data
