How do I parse a string to number while destructuring?

前端 未结 8 1056
[愿得一人]
[愿得一人] 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:58

    There is a super hacky way of doing this using a getter defined on String.prototype as a helper function.

    (You probably don't want to do that)

    Object.defineProperty (String.prototype, "asNumber",{
       get: function () { return +this}
    });
    let input = {latitude: "17.0009", longitude: "82.2108"}
    let {latitude:{asNumber:latitude},
         longitude: {asNumber:longitude}} = input
    
    console.log (latitude, longitude)

    Let's break that down into simpler steps.

    //Extending the `String` prototype means every string 
    //will have access to the defined property  via 
    //its prototype, so
    String.prototype.foo = function () {return `${this}.foo\`} 
    //means you can now call foo() like any other string method
    "bar".foo() //"bar.foo"`
    
    //A getter allows you to define a function that acts 
    //as a property which will be executed upon access. 
    let obj = {get getter () {console.log ('Hi');}}
    obj.getter // Hi
    
    //Combine those two and you can call functions by 
    //accessing properties of strings. 
    Object.defineProperty (String.prototype, "asNumber",{
       get: function () { return +this}
    });
    
    //Now that you have a property that is available at 
    //every string - and make it execute a function; you 
    //can convert a string to a number, simply by
    //accessing a property
    "42".asNumber //42
    
    //To make that work with destructuring assignment, 
    //you need to know about another handy feature. You 
    //can assign destructured properties to a new 
    //variable name.
    let {a:b, b:a} = {a:'a', b:'b'};
    a; //'b'
    b; //'a'
    
    //Since you can nest destructuring assignments, and 
    //every string implicitly has a 'asNumber' property, 
    //you can destructure that property as well. 
    
    let {lat: {asNumber}} = {lat: "42"};
    asNumber //42
    
    //The last thing to know is, there's apparently 
    //nothing wrong with using an existing variable as 
    //new name for a destructured property. So you can 
    //just use the `asNumber` property from the 
    //prototype and assign it to the same variable  
    //you destructured from the object.
    let {lat: {asNumber: lat}} = {lat: "42"};
    lat; //42
    

    There is nothing wrong with using the same name because only the last variable name will be introduced in the let block's scope

提交回复
热议问题