这 10 个 JS 小技巧,你可能还不知道

const data= null ?? 'data';console.log(data);// expected output: "data"const data1 = 1 ?? 4;console.log(data1);// expected output: 1
function add(a, b) {val1 = a || 1;val2 = b || 1;sum = val1 + val2;return sum;}console.log(add(0, 0)); //output:2
function add1(a, b) {val1 = a ?? 1;val2 = b ?? 1;sum = val1 + val2;return sum;}console.log(add1(0, 0)); //ouput:0
// Longhandswitch (data) {case 1:data1();break;case 2:data2();break;case 3:data();break;// And so on...}// Shorthandvar data = {1: data1,2: data2,3: data};const val = 1data[val]();function data1() {console.log("data1");}function data2() {console.log("data2");}function data() {console.log("data");}
console.log(`%cabc`, 'font-weight:bold;color:red');//Longhandif (test1) {callMethod();}//Shorthandtest1 && callMethod();
// Longhandfunction data1() {console.log('data1');};function data2() {console.log('data2');};var data3 = 1;if (data3 == 1) {data1();} else {data2();} //data1// Shorthand(data3 === 1 ? data1 : data2)(); //data1
// Longhandlet value;function returnMe() {if (!(value === undefined)) {return value;} else {return callFunction('value');}}var data = returnMe();console.log(data); //output valuefunction callFunction(val) {console.log(val);}// Shorthandfunction returnMe() {return value || callFunction('value');}
// Longhandlet mychoice: boolean;if (money > 100) {mychoice= true;} else {mychoice= false;}// Shorthandlet mychoice= (money > 10) ? true : false;//or we can use directlylet mychoice= money > 10;console.log(mychoice);
let salary = 300,checking = (salary > 100) ? 'greater 100' : (x < 50) ? 'less 50' : 'between 50 and 100';console.log(checking); // "greater than 100"
const data = {a: 1,b: 'atit',d: {test1: {test2: 'patel',},},};console.log(data.val.test1); // here val is not present in object which leads the errorError: Cannot read properties of undefined (reading 'test1')console.log(data?.val); // using this we can check if the val is present in the data or not
let data1 = 'abcd';let data2 = 'efgh';//Longhandlet data = {data1: data1, data2: data2};//Shorthandlet data = {data1, data2};
<p>heading before loads</p><script defer src="src/test.js"></script><p>heading after loads</p>
学习更多技能
请点击下方公众号
![]()
评论
