Question: Can I have an array of objects with a custom toString in JavaScript?

Question

Can I have an array of objects with a custom toString in JavaScript?

Answers 1
Added at 2016-12-28 13:12
Tags
Question

I've got an array of objects. (Use case might be solitaire cards).

I want to embed a toString for debugging them.

I'm using the following (simplified) to create them and put them into an array.

var shuffledArray = [];
var myObj = {
  a: "my val-a1",
  b: "my val-b1",
  init: function() {
    this.toString = this.a + " of " + this.b;
    return this;
  }
}.init();

shuffledArray.push(myObj);

var myObj2 = {
  a: "my val-a2",
  b: "my val-b2",
  init: function() {
    this.toString = this.a + " of " + this.b;
    return this;
  }
}.init();

shuffledArray.push(myObj2);

mappableToString = function (element) {
  return element.toString;
}

var shuffledArrayToString = shuffledArray.map(mappableToString); 

console.log("shuffled array: " + shuffledArrayToString.join(", "));

I feel like I'm doing something wrong with the map step. Can't I just join on the toString method?

Assumptions:

  • I'm aiming to use raw Javascript but am open to Underscore or JQuery.
Answers
nr: #1 dodano: 2016-12-28 13:12

You have to overwrite the default toString method with a custom method (and not a property):

function MyObject(x) {
  this.x = x;
}
MyObject.prototype.toString = function() {
  return "MyObject: " + this.x;
}


var arr = [];
for (var i = 0; i < 10; i++) {
  arr.push(new MyObject(i));
}

console.log(arr.join(", "));

Source Show
◀ Wstecz