【问题标题】:Can I have an array of objects with a custom toString in JavaScript?我可以在 JavaScript 中有一个带有自定义 toString 的对象数组吗?
【发布时间】:2017-05-12 17:27:37
【问题描述】:

我有一个对象数组。 (用例可能是纸牌)。

我想嵌入一个 toString 来调试它们。

我正在使用以下(简化)来创建它们并将它们放入一个数组中。

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(", "));

我觉得我在地图步骤中做错了。我不能只在toString 方法上使用join 吗?

假设

  • 我的目标是使用原始 Javascript,但我对 Underscore 或 JQuery 持开放态度。

【问题讨论】:

  • 您的代码有效,您期待不同的结果吗? (jsfiddle.net/uw12xxyp/1)
  • 我担心我没有使用最好的模式 - 或者错过了一些使它更复杂的东西。
  • 执行此操作的“功能”方法是创建函数toStringconcat,它们遵循同名参数的方法(或正确的中缀运算符),然后执行@987654327 @FWIW,我发现你写的更易读的惯用 JS。

标签: javascript jquery arrays dictionary functional-programming


【解决方案1】:

您必须使用自定义方法(而不是属性)overwrite the default toString method

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(", "));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-01
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-02
    • 2023-03-25
    相关资源
    最近更新 更多