How do I parse a string to number while destructuring?

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

    I would probably set things up so that each "object type" I cared about had a corresponding "parser type": an object with the same keys, but whose values are the appropriate parsing functions for each member.

    Like so:

    "use strict";
    
    var arr = {
        latitude: "17.0009",
        longitude: "82.2108"
    };
    
    function Parser(propParsers)
    {
        this.propParsers = propParsers;
        this.parse = function (obj) {
            var result = {};
            var propParsers = this.propParsers;
            Object.keys(obj).forEach(function (k) {
                result[k] = propParsers[k](obj[k]);
            });
            return result;
        };
    }
    
    var parser = new Parser({
        latitude: Number,
        longitude: Number
    });
    
    let {latitude,longitude} = parser.parse(arr);
    console.log(latitude);
    console.log(longitude);

提交回复
热议问题