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!
One line of code completes structure addition and assignment
We often use structure assignment in our daily life. We usually structure it first and then assign it. Of course, we can also complete the destructuring and assignment operations in one line. It seems very simplified. Of course, you know the readability!
let people = { name: null, age: null };
let result = { name: '张三', age: 16 };
({ name: people.name, age: people.age} = result);
console.log(people) // {"name":"张三","age":16}###
Deconstruct basic data types
We should not use such scenarios in daily life, but in fact we can also deconstruct basic data types
const {length : a} = '1234';
console.log(a) // 4
Destructuring an array to quickly get the last value
In fact, we can get the length property by destructuring and assigning values to the array, and we can do more things with this feature.
const arr = [1, 2, 3];
const { 0: first, length, [length - 1]: last } = arr;
first; // 1
last; // 3
length; // 3
Convert the subscript to Chinese zero one two three...
For daily possible lists, we need to convert the corresponding 012345 into Chinese one, two, three, four, five... In old projects, I saw that many lines were manually defined by myself, so I wrote one Such method conversion
export function transfromNumber(number){
const INDEX_MAP = ['零','一'.....]
if(!number) return
if(number === 10) return INDEX_MAP[number]
return [...number.toString()].reduce( (pre, cur) => pre + INDEX_MAP[cur] , '' )
}
Different ways to judge integers
/* 1.任何整数都会被1整除,即余数是0。利用这个规则来判断是否是整数。但是对字符串不准确 */
function isInteger(obj) {
return obj%1 === 0
}
/* 1. 添加一个是数字的判断 */
function isInteger(obj) {
return typeof obj === 'number' && obj%1 === 0
}
/* 2. 使用Math.round、Math.ceil、Math.floor判断 整数取整后还是等于自己。利用这个特性来判断是否是整数*/
function isInteger(obj) {
return Math.floor(obj) === obj
}
/* 3. 通过parseInt判断 某些场景不准确 */
function isInteger(obj) {
return parseInt(obj, 10) === obj
}
/* 4. 通过位运算符*/
function isInteger(obj) {
return (obj | 0) === obj
}
/* 5.ES6提供了Number.isInteger */
Detect the theme color of the system through css to modify the style globally
You can know the current system theme by using the attribute prefers-color-scheme of @media . Of course, you need to check the compatibility before using it.
@media (prefers-color-scheme: dark) { //... }
@media (prefers-color-scheme: light) { //... }
JavaScript can also do it easily
window.addEventListener('theme-mode', event =>{
if(event.mode == 'dark'){}
if(event.mode == 'light'){}
})
window.matchMedia('(prefers-color-scheme: dark)') .addEventListener('change', event => {
if (event.matches) {} // dark mode
})
Array randomly shuffled
Get a random number through 0.5-Math.random(), and then sort it twice to make it more thorough. However, this method is not actually random enough. If it is an enterprise-level application, it is recommended to use the second shuffling algorithm.
shuffle(arr) {
return arr.sort(() => 0.5 - Math.random()). sort(() => 0.5 - Math.random());
},
function shuffle(arr) {
for (let i = arr.length - 1; i > 0; i--) {
const randomIndex = Math.floor(Math.random() * (i + 1))
;[arr[i], arr[randomIndex]] = [arr[randomIndex], arr[i]]
}
return arr
}
Get a random Boolean value
The same principle as the previous one, obtained through random numbers, the interval of **Math.random()** is 0-0.99, and 0.5 is used to give a 50% probability in the middle
function randomBool() {
return 0.5 - Math.random()
}
Move the first item of the array to the last item
function (arr){
return arr.push(arr.shift());
}
Move the last item of the array to the first item
function(arr){
return arr.unshift(arr.pop());
}
Use set array to remove duplicates
function uniqueArr(arr){
return [...new Set(arr)]
}
DOM node smoothly scrolls to the area, top, and bottom
The native scrollTo method has no animation and is similar to anchor point jump. It is relatively stiff. You can use this method to have a smooth transition effect.
function scrollTo(element) {
element.scrollIntoView({ behavior: "smooth", block: "start" }) // 顶部
element.scrollIntoView({ behavior: "smooth", block: "end" }) // 底部
element.scrollIntoView({ behavior: "smooth"}) // 可视区域
}
Get a random color
In daily life, we often need to obtain a random color, which can be done through random numbers.
function getRandomColor(){
return `#${Math.floor(Math.random() * 0xffffff) .toString(16)}`;
}
Check if it is an empty object
You can determine whether it is an empty array by using Es6's Reflect static method to determine its length, or you can determine it through **Object.keys()**
function isEmpty(obj){
return Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
}
Boolean conversion
In some scenarios, we will define boolean values as scenarios, but in js, non-empty strings will be considered true.
function toBoolean(value, truthyValues = ['true']){
const normalizedValue = String(value).toLowerCase().trim();
return truthyValues.includes(normalizedValue);
}
toBoolean('TRUE'); // true
toBoolean('FALSE'); // false
toBoolean('YES', ['yes']); // true
Various array cloning methods
There are actually many methods of array cloning, see if there are any you haven’t seen before!
const clone = (arr) => arr.slice(0);
const clone = (arr) => [...arr];
const clone = (arr) => Array.from(arr);
const clone = (arr) => arr.map((x) => x);
const clone = (arr) => JSON.parse(JSON.stringify(arr));
const clone = (arr) => arr.concat([]);
const clone = (arr) => structuredClone(arr);
Compare two time sizes
Just get the timestamp comparison by calling getTime
function compare(a, b){
return a.getTime() > b.getTime();
}
Calculate the difference in months between two times
function monthDiff(startDate, endDate){
return Math.max(0, (endDate.getFullYear() - startDate.getFullYear()) * 12 - startDate.getMonth() + endDate.getMonth());
}
Extract year, month, day, hour, minute and second from time in one step
Time formatting is easy to solve. Get the year, month, day, hour, minutes, seconds and milliseconds in one step. Since toISOString will lose the time zone, resulting in a time difference of eight hours, so we can add eight hours before formatting.
function extract(date){
const d = new Date(new Date(date).getTime() + 8*3600*1000);
return new Date(d).toISOString().split(/[^0-9]/).slice(0, -1);
}
console.log(extract(new Date())) // ['2022', '09', '19', '18', '06', '11', '187']
Determine whether a parameter is a function
Sometimes our method needs to pass in a function callback, but its type needs to be detected. We can pass Object
Prototype method to detect, of course, this method can accurately detect any type.
function isFunction(v){
return ['[object Function]', '[object GeneratorFunction]', '[object AsyncFunction]', '[object Promise]'].includes(Object.prototype.toString.call(v));
}
Calculate the distance between two coordinates
function distance(p1, p2){
return `Math.sqrt(Math.pow(p2.x - p1.x, 2) + Math.pow(p2.y - p1.y, 2));
}
Check whether two DOM nodes overlap or not
In some scenarios, we need to determine whether the dom collides or overlaps. We can get the x1, y1, x2, y2 coordinates of the dom through getBoundingClientRect and then compare the coordinates to determine
function overlaps = (a, b) {
return (a.x1 < b.x2 && b.x1 < a.x2) || (a.y1 < b.y2 && b.y1 < a.y2);
}
Determine whether it is a NodeJs environment
The daily development of the front-end is inseparable from nodeJs. By judging the global environment, we can detect whether it is a nodeJs environment.
function isNode(){
return typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
}
Parameter summation
I have seen before that the sum is calculated in the physical and chemical form of the function. Just use one line of reduce.
function sum(...args){
return args.reduce((a, b) => a + b);
}
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!