Front-end interview question bank ( essential for interviews) Recommended: ★★★★★
Address: Front-end interview question bank
[National Day Avatar] - National Day patriotic programmer avatar! always one option fit for you!
Introduction
If you use these tips to optimize your js code, it can help you write cleaner, neater, easier to maintain code, saving you programming time.
1. Flexibly use &&
or ||
replace if
In some simple cases you can use logical operators &&
or ||
instead of if.
Code example 1:
// 繁琐的
if (isGetData) {
this.getData();
}
// 好的
isGetData && this.getData();
Code example 2:
// 繁琐的
if (res.data) {
return res.data;
} else {
return [];
}
// 好的
return res.data || [];
2. ~~
Operator rounding
~
It is a bitwise inversion operation, ~~
which is inversion twice. ~~
The function here is to remove the decimal part.
Because the operation value of bit operation is required to be an integer, the result is also an integer, so everything that undergoes bit operation will automatically become an integer.
Principle and use of !
operations The operator converts any type into Boolean
something like
Code Example 1:
let a = 1;
// 利用!!将a转换成 Boolean 值
a = !!a; // true
a = 0;
a = !!a; // false
a = {}
a = !!a; // true
Code Example 2: Use ~~
instead Math.floor()
// 取整
Math.floor(Math.random() * 50);
// 取整
~~(Math.random() * 50);
~~'1.11111'; // 1
~~'whitedress1'; // 0
~~NaN; // 0
3. Flexible use array.length
to adjust the array length or clear the array
Sometimes you need to resize an array or clear it. The most efficient way is to useArray.length
Code examples:
const array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j'];
console.log(array.length); // 10
// 调整数组大小
array.length = 4;
console.log(array.length); // 4
console.log(array); // ['a', 'b', 'c', 'd']
// 清空数组
array.length = 0;
console.log(array.length); // 0
console.log(array); // []
4. How to efficiently handle array merging
When merging arrays, it can cause serious stress on the browser, especially when dealing with large amounts of data. To keep things simple and efficient, use the Array.concat()
and Array.push.apply(arr1, arr2)
functions.
Recommended for handling smaller arrays Array.concat()
.
Code examples:
let list1 = ['a', 'b'];
let list2 = ['c', 'd'];
console.log(list1.concat(list2)); // ['a', 'b', 'c', 'd']
On larger arrays, it consumes a lot of memory when creating new arrays. To solve the problem of performance degradation, it is recommended to use Array.push.apply(arr1, arr2)
the following code examples:
let list1 = ['a', 'b', 'c', 'd', 'e'];
let list2 = ['f', 'g', 'h', 'i', 'j'];
console.log(list1.push.apply(list1, list2)); // 10
console.log(list1); // returns ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
5. Use of array filtering filter()
filter()
Very useful when filtering arrays. In this case, you can exclude data based on the characteristics of the array.
Code examples:
let ages = [32, 33, 16, 40];
ages = ages.filter(age => age >= 18);
console.log(ages); // 32,33,40
6. Quickly remove duplicates ...new Set(arr)
Suppose you have an array of duplicate values and you need to remove them. This can be achieved using a combination of extension syntax and object types. This method works for String
and Number
.
Code examples:
const cars = ['Opel', 'Bugatti', 'Opel', 'Ferrari', 'Ferrari', 'Opel'];
const unrepeated_cars = [...new Set(cars)];
console.log(unrepeated_cars); // ['Opel', 'Bugatti', 'Ferrari']
7. 正则
Combined replace()
to realize replacement function
Everyone should be familiar with this feature. However, it performs the replacement once by default. If you need batch replacement, you can use it with regular expressions.
const grammar = 'synonym synonym';
console.log(grammar.replace('synonym', 'anto')); // anto synonym
console.log(grammar.replace(/syno/, 'anto')); // 'antonym synonym'
console.log(grammar.replace(/syno/g, 'anto')); //'antonym antonym'
8. Use template characters to splice strings
Template characters use (``) characters combined with (${}), which can include variables, expressions, etc.
Code examples:
const name = '三哥';
const age = '26';
// const str = '他叫' + name + age;
const str = `他叫${name}${age}`;
9. How to check whether an object has a value
A quick trick to check if an object is empty is to use Object.keys()
this code example:
Object.keys(objectName).length // 如果返回0,则objectName为空,否则显示值的数目
10. Flexible use ?
of AND ??
operators
The optional chain operator ( ?. ) allows reading the value of a property located deep in the chain of connected objects without having to explicitly verify that each reference in the chain is valid. The function of the operator is similar to the (.) chain operator, except that it will not cause an error when the reference is null or undefined, and the return value of this expression is undefined. When used with function calls, returns undefined if the given function does not exist.
In our daily development, we often encounter errors such as Cannot read properties of undefined (reading 'XXX')
Code examples:
const obj = {};
console.log(obj.user.name); // 报错 Cannot read properties of undefined (reading 'name')
console.log(obj.user?.name); // undefined
The null coalescing operator (??) is a logical operator that returns the expression on the right if the expression on the left is null
or , otherwise it returns the expression on the left. Code examples:undefined
null ?? 1; // 1
undefined ?? 2; // 2
true ?? 1; // true
Front-end interview question bank ( essential for interviews) Recommended: ★★★★★
Address: Front-end interview question bank
[National Day Avatar] - National Day patriotic programmer avatar! always one option fit for you!