Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

ecmascript 6 - ES6: change a value while destructuring

Lets say I have an object

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.

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
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's possible, although it's a hack that hurts readability, might produce an error (if the object will contain the fake property in the future), and shouldn't be used in a real product.

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...