ES6在破坏时更改值 [英] ES6 change a value while destructing

查看:76
本文介绍了ES6在破坏时更改值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个对象

const obj = { width: 100, height: 200 }

我希望将该对象传递给方法

I wish to pass that object to a method

myFunc( obj );

在该方法中,我希望拉出高度,但同时要减去一个值。我只希望这样做一次,此后它永远不会改变。

Inside that method I wish to pull out the height, but at the same time subtract a value. I only wish to do this once and after that it will never change.

执行以下操作将使我得到想要的正确高度,例如150。

Doing the following will get me the correct height I want of say 150.

let {height: localHeight} = obj;
localHeight = localHeight - 50;

如何单行执行以上操作?
这样的东西-但我知道这不起作用。

How do I do the above in a single line ? Something like this - but I know this doesn't work.

const { height: (localHeight = localHeight - 50) } = obj


推荐答案

尽管这是一种会损害可读性的hack,但可能会产生错误(如果该对象将来会包含假属性),并且不应在实际产品中使用。

您可以解构不存在的属性,并使用默认值进行减法。

You can destructure a non existing property, and use the default value to do the subtraction.

const obj = { width: 100, height: 200 }

const { height, localHeight = height - 50 } = obj

console.log(localHeight)

这篇关于ES6在破坏时更改值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆