需要创建一个函数,将我自己创建的范围对象转换为字符串?

时间:2012-08-02 11:13:47

标签: javascript

下面是我用来在整个程序中创建范围对象的代码

function parseRangeString(id, range) {
    var myRangeString = range;
    var myRangeStringArray = myRangeString.split(/[\s]+/);
    var myMax;
    var myMin;
    var myMinOp;
    var myMaxOp;
    var myMaxInc = false;
    var myMinInc = false;
    var op1;
    var op2;
    var cons1;
    var cons2;
    op1 = myRangeStringArray[0];
    cons1 = parseFloat(myRangeStringArray[1]);
    if (myRangeStringArray[2] != null) {
        op2 = myRangeStringArray[3];
        cons2 = parseFloat(myRangeStringArray[4]);
    }
    if (cons1 < cons2) {
        myMin = cons1;
        myMinOp = op1;
        myMax = cons2;
        myMaxOp = op2;
    } else {
        myMin = cons2;
        myMinOp = op2;
        myMax = cons1;
        myMaxop = op1;
    }
    if (myMaxOp.indexOf('=') != -1) {
        myMaxInc = true;
    }
    if (myMinOp.indexOf('=') != -1) {
        myMinInc = true;
    }
    firstRange = new Range(id, myMin, myMax, myMinInc, myMaxInc); //gives back a range object
    return firstRange;
}

现在我需要创建另一个将范围对象转换为字符串的函数,需要帮助,因为我被卡住了!

2 个答案:

答案 0 :(得分:2)

您可以覆盖javascript对象上的标准toString函数,使其返回您想要的任何内容。考虑这个例子(demo):

var a = { some_property:'this could be coming from the user' }; // create a new object
a.toString = function(){
    // in here, the "this" will point to the object in "a" variable. (well, at least mot of the times)
    return this.some_property;
};
console.log(''+a); // force the object to string

如果您创建了大量这样的对象,请考虑使用prototype来放置toString函数,效率更高,MDN有great examples

答案 1 :(得分:-1)

我想我每天都会给出相同的答案。 :)

JSON.stringify( range );