Converting an object to a string

后端 未结 30 2502
北荒
北荒 2020-11-22 03:29

How can I convert a JavaScript object into a string?

Example:

var o = {a:1, b:2}
console.log(o)
console.log(\'Item: \' + o)

Output:

30条回答
  •  天命终不由人
    2020-11-22 04:26

    var o = {a:1, b:2};
    
    o.toString=function(){
      return 'a='+this.a+', b='+this.b;
    };
    
    console.log(o);
    console.log('Item: ' + o);
    

    Since Javascript v1.0 works everywhere (even IE) this is a native approach and allows for a very costomised look of your object while debugging and in production https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/toString

    Usefull example

    var Ship=function(n,x,y){
      this.name = n;
      this.x = x;
      this.y = y;
    };
    Ship.prototype.toString=function(){
      return '"'+this.name+'" located at: x:'+this.x+' y:'+this.y;
    };
    
    alert([new Ship('Star Destroyer', 50.001, 53.201),
    new Ship('Millennium Falcon', 123.987, 287.543),
    new Ship('TIE fighter', 83.060, 102.523)].join('\n'));//now they can battle!
    //"Star Destroyer" located at: x:50.001 y:53.201
    //"Millennium Falcon" located at: x:123.987 y:287.543
    //"TIE fighter" located at: x:83.06 y:102.523
    

    Also, as a bonus

    function ISO8601Date(){
      return this.getFullYear()+'-'+(this.getMonth()+1)+'-'+this.getDate();
    }
    var d=new Date();
    d.toString=ISO8601Date;//demonstrates altering native object behaviour
    alert(d);
    //IE6   Fri Jul 29 04:21:26 UTC+1200 2016
    //FF&GC Fri Jul 29 2016 04:21:26 GMT+1200 (New Zealand Standard Time)
    //d.toString=ISO8601Date; 2016-7-29
    

提交回复
热议问题