JavaScript Common Tricks

Object property manipulation

Object takes value by dynamic property name

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

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

insert image description here

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

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

Add properties to objects based on conditions

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

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

insert image description here

The && operator returns the last evaluated expression if each operand evaluates to true.
So an object {age: 16} is returned, which is then expanded as 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); 

insert image description here

Check if property exists in object

You can use the inkeyword to check whether a property exists in a JavaScript object.

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

Object destructuring with dynamic keys

We know that when an object is destructed, you can use :to rename the destructed properties.
But, did you know that when the key name is dynamic, it is also possible to destructure the properties of the object?

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

insert image description here

Now, we destructure the property with dynamic keys:

const templates = {
    
    
  'hello': 'Hello there',
  'bye': 'Good bye'
};
const templateName = 'bye';

const {
    
     [templateName]: template } = templates;

console.log(template); // Good bye

flattened array

There is a method on the prototype Array flatthat makes 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 } ]

insert image description here
You can also define a depth level, specifying how deeply a nested array structure should be flattened. E.g:

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

insert image description here





value manipulation

Null ??Coalescing Operator

??Operators are useful when we want to check if a variable is null or undefined .

When its left operand is null or undefined, it returns the right operand, otherwise it returns the 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 we can use the ||operator but there is a difference between the two, and you may think 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

optional chain?.

Do we often encounter errors like this:
TypeError: Cannot read property ‘foo’ of null.
This is an annoying problem for every Yi developer. Optional chaining was introduced to solve this problem. Lets come 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 optional chaining of functions like this:

const person = {
    
    
  firstName: '前端',
  lastName: '开发',
  printName: function () {
    
    
    return `${
      
      this.firstName} ${
      
      this.lastName}`;
  },
};

console.log(person.printName()); // '前端 开发'
console.log(persone.doesNotExist?.()); // undefined

String and Integer Conversion

+Use the operator to quickly convert strings to numbers:

const stringNumer = '123';

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

To quickly convert a number to a string, you can also use the +operator 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 are less clear and less readable in code.
Therefore, the actual development needs to be carefully selected and used.

!!use operator

!! Operators 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

Check for false values ​​in an array

Everyone should have used the array method: filter、some、every, these methods can be used with the Booleanmethod 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 Booleanas the callback function. BooleanThe function itself takes one argument and returns trueor false. so:

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

Equivalent to:

myArray.filter(Boolean);

Object.entries

Most developers use the Object.keysmethod to iterate over objects.
This method only returns an array of object keys, not values. We can use Object.entriesto 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]}`);
});

insert image description here

// 使用 entries 获取键和值
Object.entries(person).forEach(([key, value]) => {
    
    
  console.log(`${
      
      key} is ${
      
      value}`);
});

// name is 前端开发
// age is 20

Both methods above return the same result, but Object.entries is easier to get the key-value pair.

number separator

You can use an underscore as a number separator, which makes it easy to count the number of zeros in a number.

// 难以阅读
const billion = 1000000000;

// 易于阅读
const readableBillion = 1000_000_000;

console.log(readableBillion) //1000000000

The underscore separator can also be used for BigInt numbers, as in the following example:

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

replaceAll method

In JS, to replace all occurrences of a string with another string, we need to use a regular expression like this:

const str = 'Red-Green-Blue';

// 只规制第一次出现的
str.replace('-', ' '); // Red Green-Blue

// 使用 RegEx 替换所有匹配项
str.replace(/\-/g, ' '); // Red Green Blue

But in ES12, replaceAlla is added to String.prototype, which replaces all occurrences of a string with another string value.

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

logical assignment operator

The logical assignment operator is a combination of the logical operator &&、||、??and assignment operator =.

const a = 1;
const b = 2;

a &&= b;
console.log(a); // 2

// 上面等价于
a && (a = b);

// 或者
if (a) {
    
    
  a = b
}

Check if athe value of is true, and if so, update athe value of . The same thing can be done using the logical OR ||operator .

const a = null;
const b = 3;

a ||= b;
console.log(a); // 3

// 上面等价于
a || (a = b);

Use the null coalescing operator??:

const a = null;
const b = 3;

a ??= b;
console.log(a); // 3

// 上面等价于
if (a === null || a === undefined) {
    
    
  a = b;
}

Note: The ??operator only nullchecks undefinedthe value of or .

Edit anything on the page

Related to front-end JavaScript, design mode lets you edit any content on the page. Just open a browser console and type the following.

document.designMode = 'on';

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/weiguang102/article/details/124165158