Home  >  Article  >  Web Front-end  >  Summarize 15 JavaScript development skills (organized and shared)

Summarize 15 JavaScript development skills (organized and shared)

WBOY
WBOYforward
2022-01-06 17:37:291749browse

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:juejin.im. If there is any infringement, please contact admin@php.cn delete