这 10 个 JS 小技巧,你可能还不知道
前端达人
共 3516字,需浏览 8分钟
·
2021-11-10 08:47
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
// Longhand
switch (data) {
case 1:
data1();
break;
case 2:
data2();
break;
case 3:
data();
break;
// And so on...
}
// Shorthand
var data = {
1: data1,
2: data2,
3: data
};
const val = 1
data[val]();
function data1() {
console.log("data1");
}
function data2() {
console.log("data2");
}
function data() {
console.log("data");
}
console.log(`%cabc`, 'font-weight:bold;color:red');
//Longhand
if (test1) {
callMethod();
}
//Shorthand
test1 && callMethod();
// Longhand
function 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
// Longhand
let value;
function returnMe() {
if (!(value === undefined)) {
return value;
} else {
return callFunction('value');
}
}
var data = returnMe();
console.log(data); //output value
function callFunction(val) {
console.log(val);
}
// Shorthand
function returnMe() {
return value || callFunction('value');
}
// Longhand
let mychoice: boolean;
if (money > 100) {
mychoice= true;
} else {
mychoice= false;
}
// Shorthand
let mychoice= (money > 10) ? true : false;
//or we can use directly
let 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 error
Error: 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';
//Longhand
let data = {data1: data1, data2: data2};
//Shorthand
let data = {data1, data2};
<p>heading before loads</p>
<script defer src="src/test.js"></script>
<p>heading after loads</p>
学习更多技能
请点击下方公众号
评论