开发者的生存总是在学习新的货色,跟上变动不应该比当初更难,我的动机是介绍所有JavaScript的最佳实际,比方简写性能,作为一个前端开发者,咱们必须晓得,让咱们的生存在2021年变得更轻松。
你可能做了很长时间的JavaScript开发,但有时你可能没有更新最新的个性,这些个性能够解决你的问题,而不须要做或编写一些额定的代码。这些技术能够帮忙您编写洁净和优化的JavaScript代码。此外,这些主题能够帮忙你为2021年的JavaScript面试做筹备。
1.如果有多个条件
咱们能够在数组中存储多个值,并且能够应用数组 include
办法。
//Longhandif (x === 'abc' || x === 'def' || x === 'ghi' || x ==='jkl') { //logic}//Shorthandif (['abc', 'def', 'ghi', 'jkl'].includes(x)) { //logic}
2.如果为真…否则简写
这对于咱们有 if-else
条件,外面不蕴含更大的逻辑时,是一个较大的捷径。咱们能够简略的应用三元运算符来实现这个简写。
// Longhandlet test: boolean;if (x > 100) { test = true;} else { test = false;}// Shorthandlet test = (x > 10) ? true : false;//or we can use directlylet test = x > 10;console.log(test);
当咱们有嵌套条件时,咱们能够采纳这种形式。
let x = 300,test2 = (x > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';console.log(test2); // "greater than 100"
3.申明变量
当咱们要申明两个具备独特值或独特类型的变量时,能够应用此简写模式。
//Longhand let test1;let test2 = 1;//Shorthand let test1, test2 = 1;
4.Null, Undefined,空查看
当咱们创立新的变量时,有时咱们想查看咱们援用的变量的值是否为空或undefined。JavaScript的确有一个十分好的简写工具来实现这些性能。
// Longhandif (test1 !== null || test1 !== undefined || test1 !== '') { let test2 = test1;}// Shorthandlet test2 = test1 || '';
5.null值检查和调配默认值
let test1 = null, test2 = test1 || '';console.log("null check", test2); // output will be ""
6.undefined值检查和调配默认值
let test1 = undefined, test2 = test1 || '';console.log("undefined check", test2); // output will be ""
正常值查看
let test1 = 'test', test2 = test1 || '';console.log(test2); // output: 'test'
7.将值调配给多个变量
当咱们解决多个变量并心愿将不同的值调配给不同的变量时,此简写技术十分有用。
//Longhand let test1, test2, test3;test1 = 1;test2 = 2;test3 = 3;//Shorthand let [test1, test2, test3] = [1, 2, 3];
8.赋值运算符简写
咱们在编程中解决很多算术运算符,这是将运算符调配给JavaScript变量的有用技术之一。
// Longhandtest1 = test1 + 1;test2 = test2 - 1;test3 = test3 * 20;// Shorthandtest1++;test2--;test3 *= 20;
9.如果存在简写
这是咱们大家都在应用的罕用简写之一,但依然值得一提。
// Longhandif (test1 === true) or if (test1 !== "") or if (test1 !== null)// Shorthand //it will check empty string,null and undefined tooif (test1)
留神:如果test1有任何值,它将在if循环后进入逻辑,该运算符次要用于 null
或 undefined
的查看。
10.多个条件的AND(&&)运算符
如果仅在变量为 true
的状况下才调用函数,则能够应用 &&
运算符。
//Longhand if (test1) { callMethod(); } //Shorthand test1 && callMethod();
11.foreach循环简写
这是迭代的罕用简写技术之一。
// Longhandfor (var i = 0; i < testData.length; i++)// Shorthandfor (let i in testData) or for (let i of testData)
每个变量的数组
function testData(element, index, array) { console.log('test[' + index + '] = ' + element);}[11, 24, 32].forEach(testData);// logs: test[0] = 11, test[1] = 24, test[2] = 32
12.return中比拟
咱们也能够在return语句中应用比拟。它将防止咱们的5行代码,并将它们缩小到1行。
// Longhandlet test;function checkReturn() { if (!(test === undefined)) { return test; } else { return callMe('test'); }}var data = checkReturn();console.log(data); //output testfunction callMe(val) { console.log(val);}// Shorthandfunction checkReturn() { return test || callMe('test');}
13.箭头函数
//Longhand function add(a, b) { return a + b; } //Shorthand const add = (a, b) => a + b;
更多示例。
function callMe(name) { console.log('Hello', name);}callMe = name => console.log('Hello', name);
14.短函数调用
咱们能够应用三元运算符来实现这些性能。
// Longhandfunction test1() { console.log('test1');};function test2() { console.log('test2');};var test3 = 1;if (test3 == 1) { test1();} else { test2();}// Shorthand(test3 === 1? test1:test2)();
15. Switch简写
咱们能够将条件保留在键值对象中,并能够依据条件应用。
// Longhandswitch (data) { case 1: test1(); break; case 2: test2(); break; case 3: test(); break; // And so on...}// Shorthandvar data = { 1: test1, 2: test2, 3: test};data[something] && data[something]();
16.隐式返回简写
应用箭头函数,咱们能够间接返回值,而不用编写return语句。
//longhandfunction calculate(diameter) { return Math.PI * diameter}//shorthandcalculate = diameter => ( Math.PI * diameter;)
17.小数基数指数
// Longhandfor (var i = 0; i < 10000; i++) { ... }// Shorthandfor (var i = 0; i < 1e4; i++) {
18.默认参数值
//Longhandfunction add(test1, test2) { if (test1 === undefined) test1 = 1; if (test2 === undefined) test2 = 2; return test1 + test2;}//shorthandadd = (test1 = 1, test2 = 2) => (test1 + test2);add() //output: 3
19.扩大运算符简写
//longhand// joining arrays using concatconst data = [1, 2, 3];const test = [4 ,5 , 6].concat(data);//shorthand// joining arraysconst data = [1, 2, 3];const test = [4 ,5 , 6, ...data];console.log(test); // [ 4, 5, 6, 1, 2, 3]
对于克隆,咱们也能够应用扩大运算符。
//longhand// cloning arraysconst test1 = [1, 2, 3];const test2 = test1.slice()//shorthand// cloning arraysconst test1 = [1, 2, 3];const test2 = [...test1];
20.模板文字
如果您厌倦了在单个字符串中应用 +
来连贯多个变量,那么这种简写能够打消您的头痛。
//longhandconst welcome = 'Hi ' + test1 + ' ' + test2 + '.'//shorthandconst welcome = `Hi ${test1} ${test2}`;
21.多行字符串简写
当咱们在代码中解决多行字符串时,能够应用以下性能:
//longhandconst data = 'abc abc abc abc abc abc\n\t' + 'test test,test test test test\n\t'//shorthandconst data = `abc abc abc abc abc abc test test,test test test test`
22.对象属性调配
let test1 = 'a'; let test2 = 'b';//Longhand let obj = {test1: test1, test2: test2}; //Shorthand let obj = {test1, test2};
23.将字符串转换成数字
//Longhand let test1 = parseInt('123'); let test2 = parseFloat('12.3'); //Shorthand let test1 = +'123'; let test2 = +'12.3';
24.用解构简写
//longhandconst test1 = this.data.test1;const test2 = this.data.test2;const test2 = this.data.test3;//shorthandconst { test1, test2, test3 } = this.data;
25.用Array.find简写
当咱们的确有一个对象数组并且咱们想要依据对象属性查找特定对象时,find办法的确很有用。
const data = [ { type: 'test1', name: 'abc' }, { type: 'test2', name: 'cde' }, { type: 'test1', name: 'fgh' },]function findtest1(name) { for (let i = 0; i < data.length; ++i) { if (data[i].type === 'test1' && data[i].name === name) { return data[i]; } }}//ShorthandfilteredData = data.find(data => data.type === 'test1' && data.name === 'fgh');console.log(filteredData); // { type: 'test1', name: 'fgh' }
26.查找条件简写
如果咱们有代码来查看类型,依据类型须要调用不同的办法,咱们能够抉择应用多个else ifs或者switch,然而如果咱们有比这更好的简写办法呢?
// Longhandif (type === 'test1') { test1();}else if (type === 'test2') { test2();}else if (type === 'test3') { test3();}else if (type === 'test4') { test4();} else { throw new Error('Invalid value ' + type);}// Shorthandvar types = { test1: test1, test2: test2, test3: test3, test4: test4}; var func = types[type];(!func) && throw new Error('Invalid value ' + type); func();
27.按位索引简写
当咱们遍历数组以查找特定值时,咱们的确应用 indexOf()
办法,如果找到更好的办法该怎么办?让咱们看看这个例子。
//longhandif(arr.indexOf(item) > -1) { // item found }if(arr.indexOf(item) === -1) { // item not found}//shorthandif(~arr.indexOf(item)) { // item found}if(!~arr.indexOf(item)) { // item not found}
按位(〜
)运算符将返回除-1以外的任何值的实在值。否定它就像做 ~~
一样简略。另外,咱们也能够应用 include()
函数:
if (arr.includes(item)) { // true if the item found}
28.Object.entries()
此函数有助于将对象转换为对象数组。
const data = { test1: 'abc', test2: 'cde', test3: 'efg' };const arr = Object.entries(data);console.log(arr);/** Output:[ [ 'test1', 'abc' ], [ 'test2', 'cde' ], [ 'test3', 'efg' ]]**/
29.Object.values()
这也是ES8中引入的一项新性能,该性能执行与 Object.entries()
相似的性能,但没有要害局部:
const data = { test1: 'abc', test2: 'cde' };const arr = Object.values(data);console.log(arr);/** Output:[ 'abc', 'cde']**/
30.双按位简写
双重NOT按位运算符办法仅实用于32位整数)
// LonghandMath.floor(1.9) === 1 // true// Shorthand~~1.9 === 1 // true
31.反复一个字符串屡次
要一次又一次地反复雷同的字符,咱们能够应用for循环并将它们增加到同一循环中,然而如果咱们有一个简写办法呢?
//longhand let test = ''; for(let i = 0; i < 5; i ++) { test += 'test '; } console.log(str); // test test test test test //shorthand 'test '.repeat(5);
32.在数组中查找最大值和最小值
const arr = [1, 2, 3]; Math.max(…arr); // 3Math.min(…arr); // 1
33.从字符串中获取字符
let str = 'abc';//Longhand str.charAt(2); // c//Shorthand Note: If we know the index of the array then we can directly use index insted of character.If we are not sure about index it can throw undefinedstr[2]; // c
34.数学指数幂函数的简写
//longhandMath.pow(2,3); // 8//shorthand2**3 // 8