search
HomeWeb Front-endFront-end Q&ASummarize 15 JavaScript development skills (organized and shared)

This article will share with you some techniques that are often used in projects. JavaScript has many cool features that most beginners and intermediate developers don’t know. I hope everyone has to help.

Summarize 15 JavaScript development skills (organized and shared)

1. Conditionally add attributes to an object

We can use the expansion operator (. ..) to quickly add properties to JS objects conditionally.

const condition = true;
const person = {
  id: 1,
  name: 'John Doe',
  ...(condition && { age: 16 }),
};

The && operator returns the last evaluated expression if each operand evaluates to true. So an object {age: 16} is returned, which is then expanded to be part of the person object.

If condition is false, JavaScript will do something like this:

const person = {
  id: 1,
  name: '前端小智',
  ...(false), 
};
// 展开 `false` 对对象没有影响
console.log(person); // { id: 1, name: 'John Doe' }

2. Check whether the attribute exists in the object

You can use the in keyword to check whether a certain attribute exists in the JavaScript object.

const person = { name: '前端小智', salary: 1000 };
console.log('salary' in person); // true
console.log('age' in person); // false

3. Dynamic property names in objects

Setting object properties using dynamic keys is simple. Just use ['key name'] to add properties:

const dynamic = 'flavour';
var item = {
  name: '前端小智',
  [dynamic]: '巧克力'
}
console.log(item); // { name: '前端小智', flavour: '巧克力' }

The same trick can be used to reference object properties using dynamic keys:

const keyName = 'name';
console.log(item[keyName]); // returns '前端小智'

4. Use dynamic Object destructuring by key

We know that when destructuring an object, you can use: to rename the destructured attributes. But, did you know that you can also deconstruct the properties of an object when the key name is dynamic?

const person = { id: 1, name: '前端小智' };
const { name: personName } = person;
console.log(personName); // '前端小智'

Now, we use dynamic keys to destructure properties:

const templates = {
  'hello': 'Hello there',
  'bye': 'Good bye'
};
const templateName = 'bye';
const { [templateName]: template } = templates;
console.log(template); // Good bye

5. Null value merging?? Operator

The ?? operator is useful when we want to check whether a variable is null or undefined. When its left operand is null or undefined, it returns its right operand, otherwise it returns its left operand.

const foo = null ?? 'Hello';
console.log(foo); // 'Hello'
const bar = 'Not null' ?? 'Hello';
console.log(bar); // 'Not null'
const baz = 0 ?? 'Hello';
console.log(baz); // 0

In the third example, 0 is returned because even though 0 is considered false in JS, it is not null or undefined. You may think that we can use the || operator, but there is a difference between the two.

You may think that we can use the || operator here, but there is a difference between the two.

const cannotBeZero = 0 || 5;
console.log(cannotBeZero); // 5
const canBeZero = 0 ?? 5;
console.log(canBeZero); // 0

6. Optional chain?.

Do we often encounter such errors: TypeError: Cannot read property 'foo' of null. This is an annoying problem for every developer. Optional chaining was introduced to solve this problem. Let’s take a look:

const book = { id:1, title: 'Title', author: null };
// 通常情况下,你会这样做
console.log(book.author.age) // throws error
console.log(book.author && book.author.age); // null
// 使用可选链
console.log(book.author?.age); // undefined
// 或深度可选链
console.log(book.author?.address?.city); // undefined

You can also use the following function optional chain:

const person = {
  firstName: '前端',
  lastName: '小智',
  printName: function () {
    return `${this.firstName} ${this.lastName}`;
  },
};
console.log(person.printName()); // '前端 小智'
console.log(persone.doesNotExist?.()); // undefined

7. Use the !! operator

!! Operator can be used to quickly convert the result of an expression to a Boolean value (true or false):

const greeting = 'Hello there!';
console.log(!!greeting) // true
const noGreeting = '';
console.log(!!noGreeting); // false

8. String and Integer Conversion

Use operators to quickly convert strings to numbers:

const stringNumer = '123';
console.log(+stringNumer); //123
console.log(typeof +stringNumer); //'number'

To quickly convert numbers to strings, you can also use operators, followed by an empty string:

const myString = 25 + '';
console.log(myString); //'25'
console.log(typeof myString); //'string'

These type conversions are very convenient, but they result in less clarity and code readability. Therefore, actual development requires careful selection and use.

9. Check for false values ​​in the array

Everyone should have used array methods: filter, some, every, these methods can be used together Boolean method to test true and false values.

const myArray = [null, false, 'Hello', undefined, 0];
// 过滤虚值
const filtered = myArray.filter(Boolean);
console.log(filtered); // ['Hello']
// 检查至少一个值是否为真
const anyTruthy = myArray.some(Boolean);
console.log(anyTruthy); // true
// 检查所有的值是否为真
const allTruthy = myArray.every(Boolean);
console.log(allTruthy); // false

Here’s how it works. We know that these array methods accept a callback function, so we pass a Boolean as the callback function. The Boolean function itself accepts a parameter and returns true or false depending on the truth of the parameter. So:

myArray.filter(val => Boolean(val));

is equivalent to:

myArray.filter(Boolean);

10. Flattening arrays

There is a method on the prototype Array flat can make a single array from an array of arrays.

const myArray = [{ id: 1 }, [{ id: 2 }], [{ id: 3 }]];
const flattedArray = myArray.flat(); 
//[ { id: 1 }, { id: 2 }, { id: 3 } ]

You can also define a depth level, specifying how deep a nested array structure should be flattened. For example:

const arr = [0, 1, 2, [[[3, 4]]]];
console.log(arr.flat(2)); // returns [0, 1, 2, [3,4]]

11.Object.entries

Most developers use the Object.keys method to iterate over objects. This method only returns an array of object keys, not values. We can use Object.entries to get keys and values.

const person = {
  name: '前端小智',
  age: 20
};
Object.keys(person); // ['name', 'age']
Object.entries(data); // [['name', '前端小智'], ['age', 20]]

To iterate over an object we can do the following:

Object.keys(person).forEach((key) => {
  console.log(`${key} is ${person[key]}`);
});
// 使用 entries 获取键和值
Object.entries(person).forEach(([key, value]) => {
  console.log(`${key} is ${value}`);
});
// name is 前端小智
// age is 20

Both of the above methods return the same results, but Object.entries is easier to get the key-value pairs.

12.replaceAll method

In JS, to replace all occurrences of a string with another string, we need to use the following Regular expression shown:

const str = 'Red-Green-Blue';
// 只规制第一次出现的
str.replace('-', ' '); // Red Green-Blue
// 使用 RegEx 替换所有匹配项
str.replace(/\-/g, ' '); // Red Green Blue

But in ES12, a new method called replaceAll was added to String.prototype, which replaces all occurrences of a string with another string value.

str.replaceAll('-', ' '); // Red Green Blue

13. Number separator

You can use underscores as number separators, which makes it easy to count the number of 0s in the number.

// 难以阅读
const billion = 1000000000;
// 易于阅读
const readableBillion = 1000_000_000;
console.log(readableBillion) //1000000000

下划线分隔符也可以用于BigInt数字,如下例所示

const trillion = 1000_000_000_000n;
console.log(trillion); // 1000000000000

14.document.designMode

与前端的JavaScript有关,设计模式让你可以编辑页面上的任何内容。只要打开浏览器控制台,输入以下内容即可。

document.designMode = 'on';

15.逻辑赋值运算符

逻辑赋值运算符是由逻辑运算符&&、||、??和赋值运算符=组合而成。

const a = 1;
const b = 2;
a &&= b;
console.log(a); // 2
// 上面等价于
a && (a = b);
// 或者
if (a) {
  a = b
}

检查a的值是否为真,如果为真,那么更新a的值。使用逻辑或 ||操作符也可以做同样的事情。

const a = null;
const b = 3;
a ||= b;
console.log(a); // 3
// 上面等价于
a || (a = b);

使用空值合并操作符 ??:

const a = null;
const b = 3;
a ??= b;
console.log(a); // 3
// 上面等价于
if (a === null || a === undefined) {
  a = b;
}

注意:??操作符只检查 null 或 undefined 的值。

【相关推荐:javascript学习教程

The above is the detailed content of Summarize 15 JavaScript development skills (organized and shared). 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
es6数组怎么去掉重复并且重新排序es6数组怎么去掉重复并且重新排序May 05, 2022 pm 07:08 PM

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

JavaScript的Symbol类型、隐藏属性及全局注册表详解JavaScript的Symbol类型、隐藏属性及全局注册表详解Jun 02, 2022 am 11:50 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

原来利用纯CSS也能实现文字轮播与图片轮播!原来利用纯CSS也能实现文字轮播与图片轮播!Jun 10, 2022 pm 01:00 PM

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

JavaScript对象的构造函数和new操作符(实例详解)JavaScript对象的构造函数和new操作符(实例详解)May 10, 2022 pm 06:16 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

JavaScript面向对象详细解析之属性描述符JavaScript面向对象详细解析之属性描述符May 27, 2022 pm 05:29 PM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

javascript怎么移除元素点击事件javascript怎么移除元素点击事件Apr 11, 2022 pm 04:51 PM

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

整理总结JavaScript常见的BOM操作整理总结JavaScript常见的BOM操作Jun 01, 2022 am 11:43 AM

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach是es6里的吗foreach是es6里的吗May 05, 2022 pm 05:59 PM

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。

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)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools