How do I parse a string to number while destructuring?

前端 未结 8 1050
[愿得一人]
[愿得一人] 2020-12-05 10:23

I am trying to experiment around destructuring assignment. Now I have a case which I trying to cop up with destructuring itself.

For example, I have an input like th

8条回答
  •  自闭症患者
    2020-12-05 10:52

    Whilst you cannot perform type conversion within the destructuring expression itself, a possible alternative/workaround could be to destructure the properties within the arguments of a function, and then return an array with the new types within it.

    For example, something like the following:

    const input = {latitude: "17.0009", longitude: "82.2108"}
    const [lat, lng] = (({latitude:a, longitude:b}) => [+a, +b])(input);
    
    console.log(typeof lat, typeof lng); // number number

    However, for something like this, I wouldn't use destructuring and probably would resort to regular dot notation:

    const input = {latitude: "17.0009", longitude: "82.2108"}
    const lat = +input.latitude;
    const lng = +input.longitude;
    
    console.log(typeof lat, typeof lng); // number number

提交回复
热议问题