英文 | https://medium.com/stackanatomy/top-javascript-shorthand-techniques-64920294f0c8
const restaurant = {name: "Classico Italiano",menu: ["Garlic", "Bread", "Salad", "Pizza", "Pasta"],openingHours: {friday: { open: 11, close: 24 },saturday: { open: 12, close: 23 },},};// Longhandconsole.log("value of friday in restaurant:", restaurant.openingHours.friday);console.log("value of name in restaurant:", restaurant.name);// Shorthandconst { name, openingHours } = restaurant;const { openingHours: { friday } } = restaurant;//we can go further and get the value of open in fridayconst { openingHours: { friday: { open } } } = restaurant;console.log(name, friday, open);
02)、Object.entries()
Object.entries() 是 ES8 中引入的一项功能,它允许您将文字对象转换为键/值对数组。
const credits = {producer: "Open Replay",editor: "Federico",assistant: "John",};const arr = Object.entries(credits);console.log(arr);Output: [["producer", "Open Replay"],["editor", "Federico"],["assistant", "John"],];
03)、Object.values()
Object.values() 也是 ES8 中引入的新特性,与 Object 具有类似的功能。entries() 但这没有关键部分:
const credits = {producer: "Open Replay",editor: "Federico",assistant: "John",};const arr = Object.values(credits);console.log(arr);Output: ["Open Replay", "Federico", "John"];
04)、对象循环速记
传统的 JavaScript for 循环语法是 for (let i = 0; i < x; i++) { … }。通过引用迭代器的数组长度,此循环语法可用于遍历数组。共有三个 for 循环快捷方式,它们提供了用于遍历数组中的对象的各种方法:
for…of 创建一个循环遍历内置字符串、数组和类似数组的对象,甚至是 Nodelist
for...in 在记录属性名称和值的字符串时访问数组的索引和对象文字上的键。
Array.forEach 使用回调函数对数组元素及其索引执行操作
const arr = ["Yes", "No", "Maybe"];// Longhandfor (let i = 0; i < arr.length; i++) {console.log("Here is item: ", arr[i]);}// Shorthandfor (let str of arr) {console.log("Here is item: ", str);}arr.forEach((str) => {console.log("Here is item: ", str);});for (let index in arr) {console.log(`Item at index ${index} is ${arr[index]}`);}// For object literalsconst obj = { a: 1, b: 3, c: 5 };for (let key in obj) {console.log(`Value at key ${key} is ${obj[key]}`);}
05)、对象属性简写
在 JavaScript 中定义对象字面量让生活变得更轻松。ES6 在为对象赋予属性方面提供了更多的简单性。如果变量名和对象键相同,则可以使用速记符号。
通过在对象字面量中声明变量,您可以在 JavaScript 中快速将属性分配给对象。为此,必须使用预期的键命名变量。这通常在您已经有一个与对象属性同名的变量时使用。
const a = 1;const b = 2;const c = 3;// Longhandconst obj = {a: a,b: b,c: c,};// Shorthandconst obj = { a, b, c };
06)、Javascript For 循环
如果你想要简单的 JavaScript 并且不想依赖第三方库,这个小技巧很有用。
// Longhand:const fruits = ['mango', 'peach', 'banana'];for (let i = 0; i < fruits.length; i++) { /* something */ }// Shorthand:for (let fruit of fruits) { /* something */ }
如果您想访问文字对象中的键,这也适用:
const obj = { continent: "Africa", country: "Ghana", city: "Accra" };for (let key in obj) console.log(key); // output: continent, country, city
07)、Array.forEach 的简写:
function logArrayElements(element, index, array) {console.log("a[" + index + "] = " + element);}[2, 4, 6].forEach(logArrayElements);// a[0] = 2// a[1] = 4// a[2] = 6
2、与Javascript数组相关的
01)、数组解构
ES6 的一个有趣的新增功能是解构赋值。解构是一种 JavaScript 表达式,可以将数组值或对象属性分离到单独的变量中。换句话说,我们可以通过从数组和对象中提取数据来将数据分配给变量。
const arr = [2, 3, 4];// Longhandconst a = arr[0];const b = arr[1];const c = arr[2];// Shorthandconst [a, b, c] = arr;
02)、Spread Operator
得益于 ES6 中引入的展开运算符,JavaScript 代码使用起来更加高效和愉快。它可以代替特定的数组函数。展开运算符中有一系列的三个点,我们可以用它来连接和克隆数组。
const odd = [3, 5, 7];const arr = [1, 2, 3, 4];// Longhandconst nums = [2, 4, 6].concat(odd);const arr2 = arr.slice();// Shorthandconst nums = [2, 4, 6, ...odd];const arr2 = [...arr];
与 concat() 函数不同,您可以使用扩展运算符将一个数组插入另一个数组中的任意位置。
const odd = [3, 5, 7];const nums = [2, ...odd, 4, 6]; // 2 3 5 7 4 6
3、与Javascript字符串相关
01)、多行字符串
如果您曾经发现自己需要在代码中编写多行字符串,那么您可以这样写:
// Longhandconst lorem ="Lorem, ipsum dolor sit amet" +"consectetur adipisicing elit." +" Quod eaque sint voluptatem aspernatur provident" +"facere a dolorem consectetur illo reiciendis autem" +"culpa eos itaque maxime quis iusto quisquam" +"deserunt similique, dolores dolor repudiandae!" +"Eaque, facere? Unde architecto ratione minus eaque" +"accusamus, accusantium facere, sunt" +"quia ex dolorem fuga, laboriosam atque.";
但是有一种更简单的方法,只需使用反引号即可完成。
// Shorthand:const lorem = `Lorem, ipsum dolor sit ametconsectetur adipisicing elit.Quod eaque sint voluptatem aspernatur providentfacere a dolorem consectetur illo reiciendis autemculpa eos itaque maxime quis iusto quisquamdeserunt similique, dolores dolor repudiandae!Eaque, facere? Unde architecto ratione minus eaqueaccusamus, accusantium facere, suntquia ex dolorem fuga, laboriosam atque.`;
02)、将字符串转换为数字
您的代码可能偶尔会收到必须以数字格式处理的字符串格式的数据。这不是一个大问题;我们可以快速转换它。
// Longhandconst num1 = parseInt('1000');const num2 = parseFloat('1000.01')// Shorthandconst num1 = +'1000'; //converts to int datatypeconst num2 = +'1000.01'; //converts to float data type
03)、模板文字
我们可以在不使用 (+) 的情况下将许多变量附加到字符串中。模板文字在这里派上用场。用反引号包裹你的字符串,用 ${ } 包裹你的变量,以利用模板文字。
const fullName = "Ama Johnson";const job = "teacher";const birthYear = 2000;const year = 2025;// Longhandconst Fullstr ="I am " + fullName + ", a " + (year - birthYear) + " years old " + job + ".";// Shorthandconst Fullstr = `I am ${fullName}, a ${year - birthYear} years old ${job}. `;
模板字面量为我们省去了许多使用 + 运算符连接字符串的麻烦。
4、与指数有关的
01)、指数幂速记
将第一个操作数乘以第二个操作数的幂的结果是求幂运算符 ** 返回的结果。它与 Math.pow 相同,只是 BigInts 也被接受为操作数。
// LonghandMath.pow(2, 3); //8Math.pow(2, 2); //4Math.pow(4, 3); //64// Shorthand2 ** 3; //82 ** 4; //44 ** 3; //64
02)、十进制底指数
这个可能以前见过。本质上,这是一种写整数的奇特方法,没有最后的零。例如,表达式 1e8 表示 1 后跟八个零。它表示十进制基数 100,000,000,JavaScript 将其解释为浮点类型。
// Longhandfor (let i = 0; i < 10000000; i++) { /* something */ }// Shorthandfor (let i = 0; i < 1e7; i++) { /* something */ }// All the below will evaluate to true1e0 === 1;1e1 === 10;1e2 === 100;1e3 === 1000;1e4 === 10000;1e5 === 100000;1e6 === 1000000;1e7 === 10000000;1e8 === 100000000;
5、其他操作的 JavaScript 简写
01)、短路评估
短路评估也可以替代 if...else 子句。当变量的预期值为 false 时,此快捷方式使用逻辑或运算符 || 为变量提供默认值。
let str = "";let finalStr;// Longhandif (str !== null && str !== undefined && str != "") {finalStr = str;} else {finalStr = "default string";}// Shorthandlet finalStr = str || "default string"; // 'default string'
02)、默认参数
if 语句用于定义函数参数的默认值。在 ES6 中,您可以在函数声明本身中定义默认值。如果没有传递任何值或未定义,则默认函数参数允许使用默认值初始化参数。
以前都是在函数体中测试参数值,如果没有定义就赋值。
默认情况下,JavaScript 中的函数参数是未定义的。然而,设置不同的默认设置通常是有利的。在这里,默认设置可能很有用。
// Longhandfunction volume(a, b, c) {if (b === undefined) b = 3;if (c === undefined) c = 4;return a * b * c;}// Shorthandfunction volume(a, b = 3, c = 4) {return a * b * c;}
03)、隐式返回函数
我们经常使用关键字 return 来指示函数的最终输出。单语句箭头函数将隐式返回其计算结果(该函数必须省略方括号 {} 才能这样做)。
对于多行语句,例如表达式,我们可以将返回表达式包裹在括号 () 中。
function capitalize(name) {return name.toUpperCase();}function add(numG, numH) {return numG + numH;}// Shorthandconst capitalize = (name) => name.toUpperCase();const add = (numG, numH) => numG + numH;// Shorthand TypeScript (specifying variable type)const capitalize = (name: string) => name.toUpperCase();const add = (numG: number, numH: number) => numG + numH;
04)、声明变量
在函数的开头声明变量赋值是个好主意。这种精简方法可以帮助您在一次创建大量变量时节省大量时间和空间。
// Longhandlet x;let y;let z = 3;// Shorthandlet x, y, z=3;
但是,请注意,出于易读性考虑,许多人更喜欢用手写方式声明变量。
05)、可选链接
我们可以使用点表示法访问对象的键或值。我们可以通过可选链接更进一步并读取键或值,即使我们不确定它们是否存在或是否已设置。如果键不存在,则可选链接的值未定义。
下面是一个可选链的例子:
const restaurant = {details: {name: "Classico Italiano",menu: ["Garlic", "Bread", "Salad", "Pizza"],},};// Longhandconsole.log("Name ",restaurant.hasOwnProperty("details") &&restaurant.details.hasOwnProperty("name") &&restaurant.details.name);// Shorthandconsole.log("Name:", restaurant.details?.name);
06)、双位非运算符
JavaScript 中的内置 Math 对象通常用于访问数学函数和常量。一些函数提供了有用的技术,让我们可以在不引用 Math 对象的情况下调用它们。
例如,我们可以通过使用两次按位非运算符来获得整数的 Math.floor() ~~。
const num = 7.5;// Longhandconst floorNum = Math.floor(num); // 7// Shorthandconst floorNum = ~~num; // 7
写在最后
这些是已被证明的一项宝贵技巧,因为它简洁明了,使编码变得有趣并且代码行易于记忆。但是请记住,它们的使用不能以牺牲代码的其他方面为代价。如果您觉得我今天分享的内容有用的话,请点赞我,关注我,并将它分享给你的朋友,也许能够帮助到他。
最后,感谢你的阅读,编程愉快!
学习更多技能
请点击下方公众号