7个JavaScript速记技巧,可以节省您的时间
在本文中,我们将讨论JavaScript中的7个酷炫的速记技巧,这将节省开发人员的时间。
箭头函数: JavaScript箭头函数是在ES6中引入的。该函数的主要优点是具有更短的语法。
<script>
// Longhand
function add(a, b) {
return a + b;
}
console.log(add(1,2))
// Shorthand
const add1 = (a, b) => a + b;
console.log(add1(1,2))
</script>
输出:
3
3
多行字符串: 对于多行字符串,我们通常使用加号运算符和换行转义序列 (\n)。我们可以使用反引号 (`) 更简单地实现。
<script>
// Longhand
console.log('JavaScript is a lightweight, interpreted, '
+ 'object-oriented language\nwith first-class '
+ 'functions, and is best known as the scripting '
+ 'language for Web \npages, but it is used in many'
+ 'non-browser environments as well.\n');
// Shorthand
console.log(`JavaScript is a lightweight, interpreted,
object-oriented language with first-class functions,
and is best known as the scripting language for Web
pages, but it is used in many non-browser environments
as well.`);
</script>
输出:
JavaScript is a lightweight, interpreted, object-oriented language
with first-class functions, and is best known as the scripting language for Web
pages, but it is used in manynon-browser environments as well.
JavaScript is a lightweight, interpreted,
object-oriented language with first-class functions,
and is best known as the scripting language for Web
pages, but it is used in many non-browser environments
as well.
For循环: 通常情况下,我们使用传统的for循环来遍历数组。我们可以利用for…of循环来遍历数组。我们可以使用for…in循环来访问每个值的索引。
<script>
let myArr = [50, 60, 70, 80];
// Longhand
for (let i = 0; i < myArr.length; i++) {
console.log(myArr[i]);
}
// Shorthand
// 1. for of loop
for (const val of myArr) {
console.log(val);
}
// 2. for in loop
for (const index in myArr) {
console.log(`index: {index} and value:{myArr[index]}`);
}
</script>
输出:
50
60
70
80
50
60
70
80
"index: 0 and value: 50"
"index: 1 and value: 60"
"index: 2 and value: 70"
"index: 3 and value: 80"
将字符串转换为数字: 可使用内置方法如 parseInt 和 parseFloat 来将字符串转换为数字。也可以通过在字符串值前面提供一个一元运算符(+)来实现。
<script>
// Longhand
let a = parseInt('764');
let b = parseFloat('29.3');
console.log(a,b)
// Shorthand
let c = +'764';
let d = +'29.3';
console.log(c,d)
</script>
输出:
764 29.3
764 29.3
交换两个变量: 对于交换两个变量,我们通常使用第三个变量。但是使用数组解构赋值可以轻松完成。
<script>
//Longhand
let x = 'Hello', y = 'World';
const temp = x;
x = y;
y = temp;
console.log(x,y)
//Shorthand
let a = 'Hello'
let b = 'World'
[a,b] = [b,a];
console.log(a,b)
</script>
输出:
World Hello
数组合并:
要合并两个数组,可以使用以下方法:
<script>
// Longhand
let a1 = [2, 3];
let a2 = a1.concat([6, 8]);
console.log(a2)
// Output: [2, 3, 6, 8]
// Shorthand
let a3 = [...a1, 6, 8];
console.log(a3)
// Output: [2, 3, 6, 8]
</script>
输出:
[2, 3, 6, 8]
[2, 3, 6, 8]
多个条件的检查: 对于多个值的匹配,我们可以将所有值放入一个数组中,并使用 indexOf() 或 includes() 方法。
<script>
let value = 1
// Longhand
if (value === 1 || value === 'hello' || value === 2 || value === 'world') {
console.log("Done")
}
// Shorthand 1
if ([1, 'hello', 2, 'world'].indexOf(value) >= 0) {
console.log('Done')
}
// Shorthand 2
if ([1, 'hello', 2, 'world'].includes(value)) {
console.log('Done')
}
</script>
输出:
Done
Done
Done
极客教程