search
HomeWeb Front-endJS TutorialSome 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.

Some super useful features in JavaScript over the past five years!

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'

What if the "string to be added to the beginning of the original string" parameter is not provided?

It will add spaces

in 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"

Finally, what if the "new string length we want" parameter is not provided?

It will return a

copy 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.
This string method works the same as

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

The same rules apply for parameter usage:

  • desiredStringLength 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
You may have encountered

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!

Statement
This article is reproduced at:掘金社区. If there is any infringement, please contact admin@php.cn delete
Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration)Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment