数组和对象解构功能是在javascript的es6版本中引入的。数组和对象的解构允许我们将其值存储在单独的变量中。之后,我们可以使用该变量来访问对象的特定属性的值。
在解构数组对象时我们需要关注的主要问题是默认值。例如,我们在解构对象中添加了property3变量,但是如果该对象不包含property3,则解构会将未定义的值设置为property3变量。
用户可以按照下面的示例来了解解构如何将未定义的值设置为不存在的属性。
示例在下面的示例中,我们创建了 demo_obj 对象,其中包含带有一些整数值的 x 和 y 属性。之后,我们解构 demo_obj 并尝试在 w、x、y 和 z 变量中设置其属性值。
在输出中,我们可以观察到 w 和 z 变量的值未定义,因为它不存在于 demo_obj 对象中。
<html><body> <h2>destructuring objects without default values in javascript</h2> <div id = output> </div></body><script> let output = document.getelementbyid('output'); let demo_obj = { x: 30, y: 60 } const { w, x, y, z } = demo_obj; output.innerhtml += the value of w variable is + w + <br/>; output.innerhtml += the value of x variable is + x + <br/>; output.innerhtml += the value of y variable is + y + <br/>; output.innerhtml += the value of z variable is + z + <br/>;</script></html>
从上面的例子中,用户明白了为什么我们需要在解构对象时为变量设置默认值。
语法用户在 javascript 中解构对象时可以按照以下语法设置默认值。
const { prop1, prop2 = default_value, prop3 = default_value } = { prop1 : value1, prop2 : value2};
在上面的语法中,我们解构了 prop1、prop2 和 porp3 变量中的对象。此外,我们还设置了 prop2 和 prop3 变量的默认值。
示例在下面的示例中,我们创建了包含 id、姓名和薪水的员工对象。之后,我们在 id、name、salary 和age 变量中解构雇员对象。此外,我们还使用默认值 22 初始化了年龄变量。
在输出中,我们可以观察到age变量的值为22,这是默认值,因为employee对象不包含age属性。
<html><body> <h2>destructuring objects <i> with default values </i> in javascript.</h2> <div id = output> </div></body><script> let output = document.getelementbyid('output'); let employee = { id: 12345, name: shubham, salary: 10000$, } const { id, name, salary, age = 22 } = employee; output.innerhtml += the value of id variable is + id + <br/>; output.innerhtml += the value of name variable is + name + <br/>; output.innerhtml += the value of salary variable is + salary + <br/>; output.innerhtml += the value of age variable is + age + <br/>;</script></html>
示例在下面的示例中,我们创建了表格对象并将其解构为 id、drawer、width 和 color 变量。用户可以观察到,由于表格对象不包含 width 属性,因此 width 变量的值为 4 英尺,这是默认值。
对于其他变量,它从对象属性中获取值。例如,颜色变量的默认值为黑色。尽管如此,由于该对象包含具有绿色值的颜色属性,因此将绿色指定为颜色变量的值。
<html><body> <h2>destructuring objects <i> with default values </i> in javascript</h2> <div id= output> </div></body><script> let output = document.getelementbyid('output'); let table = { id: table2, color: blue, drawers: 3, } const { id, color = black, drawers = 5, width = 4 feet } = table; output.innerhtml += the value of id variable is + id + <br/>; output.innerhtml += the value of color variable is + color + <br/>; output.innerhtml += the value of drawers variable is + drawers + <br/>; output.innerhtml += the value of width variable is + width + <br/>;</script></html>
用户在本教程中学习了如何解构具有默认值的对象。此外,用户可以在创建变量时使用一些默认值初始化变量,而不是在解构对象时为其分配一些默认值。
从上面的例子中我们可以了解到,当一个对象包含任何属性时,都会将该属性值设置为变量;否则,变量将保持默认值。
以上就是在 javascript 中解构对象时如何设置默认值?的详细内容。
