let test1 = null,
test2 = test1 || ‘’;
console.log(“null check”, test2); // output will be “”
let test1 = undefined,
test2 = test1 || ‘’;
console.log(“undefined check”, test2); // output will be “”
一般值检查
let test1 = ‘test’,
test2 = test1 || ‘’;
console.log(test2); // output: ‘test’
另外,对于上述的 4、5、6 点,都可以使用?? 操作符。
如果左边值为 null 或 undefined,就返回右边的值。默认情况下,它将返回左边的值。
const test= null ?? ‘default’;
console.log(test);
// expected output: “default”
const test1 = 0 ?? 2;
console.log(test1);
// expected output: 0
当我们想给多个不同的变量赋值时,这种技巧非常有用。
//Longhand
let test1, test2, test3;
test1 = 1;
test2 = 2;
test3 = 3;
//Shorthand
let [test1, test2, test3] = [1, 2, 3];
在编程过程中,我们要处理大量的算术运算符。这是 JavaScript 变量赋值操作符的有用技巧之一。
// Longhand
test1 = test1 + 1;
test2 = test2 - 1;
test3 = test3 * 20;
// Shorthand
test1++;
test2–;
test3 *= 20;
这是我们都在使用的一种常用的简便技巧,在这里仍然值得再提一下。
// Longhand
if (test1 === true) or if (test1 !== “”) or if (test1 !== null)
// Shorthand //it will check empty string,null and undefined too
if (test1)
注意:如果 test1 有值,将执行 if 之后的逻辑,这个操作符主要用于 null 或 undefinded 检查。
如果只在变量为 true 时才调用函数,可以使用 && 操作符。
//Longhand
if (test1) {
callMethod();
}
//Shorthand
test1 && callMethod();
这是一种常见的循环简化技巧。
// Longhand
for (var i = 0; i < testData.length; i++)
// Shorthand
for (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
我们也可以在 return 语句中使用比较,它可以将 5 行代码减少到 1 行。
// Longhand
let test;
function checkReturn() {
if (!(test === undefined)) {
return test;
} else {
return callMe(‘test’);
}
}
var data = checkReturn();
console.log(data); //output test
function callMe(val) {
console.log(val);
}
// Shorthand
function checkReturn() {
return test || callMe(‘test’);
}
//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);
我们可以使用三元操作符来实现多个函数调用。
// Longhand
function test1() {
console.log(‘test1’);
};
function test2() {
console.log(‘test2’);
};
var test3 = 1;
if (test3 == 1) {
最后
小编综合了阿里的面试题做了一份前端面试题PDF文档,里面有面试题的详细解析
虽只说了一个公司的面试,但我们可以知道大厂关注的东西并举一反三,通过一个知识点延伸到另一个知识点,这是我们要掌握的学习方法,小伙伴们在这篇有学到的请评论点赞转发告诉小编哦,谢谢大家的支持!