Why write two lines when one line of code can do it?

 Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

ternary operator

Use the ternary operator instead of the simpleif else

if (age < 18) {
  me = '小姐姐';
} else {
  me = '老阿姨';
}
复制代码

Use the ternary operator instead, and you can do it in one line

me = age < 18 ? '小姐姐' : '老阿姨';
复制代码

The complex judgment ternary operator is a bit difficult to understand

const you = "董员外"
const your = "菜鸡本鸡"
const me = you ?"点再看":your?"点赞":"分享"
复制代码

judgment

When more than one situation needs to be judged, the first idea is to use the  || OR operator

if(
    type == 1 ||
    type == 2 ||
    type == 3 ||
    type == 4 ||
){
   //...
}
复制代码

One line of includes in ES6 can do it

if( [1,2,3,4,5].includes(type) ){
   //...
}
复制代码

value

When writing code, we often use value-taking operations

const obj = {
    a:1,
    b:2,
    c:3,
}
//老的取值方式
const a = obj.a;
const b = obj.b;
const c = obj.c;
复制代码

The old way of getting the value is to directly use the object name plus the attribute name to get the value. If you use ES6's destructuring assignment, you can get it done in one line

const {a,b,c} = obj;
复制代码

Get object property value

In the process of programming, we often encounter the situation of obtaining a value and assigning it to another variable. When obtaining this value, we need to judge whether the object exists before assigning it.

if(obj && obj.name){
  const name = obj.name
}
复制代码

ES6 provides the optional concatenation operator ?.to simplify operations

const name = obj?.name;
复制代码

reverse string

Flip a string and return the flipped string

const reverse = str => str.split('').reverse().join('');

reverse('hello world');   // 'dlrow olleh'
复制代码

generate random string

Generate a random string of letters and numbers

const randomString = () => Math.random().toString(36).slice(2);
//函数调用
randomString();
复制代码

Array deduplication

Used to remove duplicates in an array

const unique = (arr) => [...new Set(arr)];

console.log(unique([1, 2, 2, 2, 3, 4, 4, 5, 6, 6]));
复制代码

Array object deduplication

To remove duplicate objects, the key value and value of the object are equal to each other, so it is called the same object

const uniqueObj = (arr, fn) =>arr.reduce((acc, v) => {if (!acc.some(x => fn(v, x))) acc.push(v);return acc;}, []);
 
uniqueObj([{id: 1, name: '大师兄'}, {id: 2, name: '小师妹'}, {id: 1, name: '大师兄'}], (a, b) => a.id == b.id)
// [{id: 1, name: '大师兄'}, {id: 2, name: '小师妹'}]
复制代码

Merge data

When we need to merge data and remove duplicate values, do you want to use for loop? ES6's spread operator can do it in one line! ! !

const a = [1,2,3];
const b = [1,5,6];
const c = [...new Set([...a,...b])];//[1,2,3,5,6]
复制代码

Check if the array is empty

Check if an array is empty, it will return a boolean value

const notEmpty = arr => Array.isArray(arr) && arr.length > 0;

notEmpty([1, 2, 3]);  // true
复制代码

swap two variables

//旧写法
let a=1;
let b=2;
let temp;
temp=a
a=b
b=temp

//新写法
[a, b] = [b, a];
复制代码

judge odd or even

const isEven = num => num % 2 === 0;

isEven(996); 
复制代码

Get a random integer between two numbers

const random = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);

random(1, 50);
复制代码

Check if date is a weekday

Pass in the date to determine whether it is a working day

const isWeekday = (date) => date.getDay() % 6 !== 0;
console.log(isWeekday(new Date(2021, 11, 11)));
// false 
console.log(isWeekday(new Date(2021, 11, 13)));
// true
复制代码

advanced

scroll to top of page

Without introducing element-ui and other frameworks, one line of code can scroll to the top

const goToTop = () => window.scrollTo(0, 0);
goToTop();
复制代码

Does the browser support touch events?

ontouchstartDetermine whether touch is supported by judging whether the browser has events

const touchSupported = () => {
  ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);
}
console.log(touchSupported());
复制代码

Whether the current device is an Apple device

The front end is often compatible with andriod and ios

const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
console.log(isAppleDevice);
// Result: will return true if user is on an Apple device
复制代码

copy content to clipboard

Use navigator.clipboard.writeText to copy text to clipboard

const copyToClipboard = (text) => navigator.clipboard.writeText(text);

copyToClipboard("双十一来了~");
复制代码

Detect if it is dark mode

It is used to detect whether the current environment is dark mode, and returns a boolean value

const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches

console.log(isDarkMode)
复制代码

website in black and white

Sometimes the website needs to turn the whole website into black and white under certain circumstances

filter:grayscale(100%)
复制代码

Just filter:grayscale(100%)put this line of code on the body, and it will be black in one go

 

Dachang interview questions share interview question bank

Front-end and back-end interview question banks (necessary for interviews) Recommended: ★★★★★

Address: front-end interview question bank   web front-end interview question bank VS java back-end interview question bank Daquan

Guess you like

Origin blog.csdn.net/weixin_42981560/article/details/130159369