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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

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

Video Face Swap

Video Face Swap

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

Hot Article

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft