在函数中返回对象时使用for-in / of的问题

问题描述

我刚在终端上打印了结果“ [object Object]的分数为0”。 结果27一切正常,直到我将函数分离为返回对象。

  1. 如果我必须返回一个对象,我如何得到27?
  2. 如何在console.log而不是[object Object]上打印“ alex”?
const alex = {
  first: [1,2,9,8],second: [3],third: [0,1,3]
};
const gordon = {
  first: [3],second: [2,4,5,6,7,8]
}

function createPlayer(object) {
  let score = 0;
  return {
    add: function() {
      for (const key in object) {
        for (const item in object[key]) {
          score += object[key][item]
        }
      }
    },result: function() {
      return `${object}\'s score is ${score}`
    }
  }
}
createPlayer(alex).add()
console.log(createPlayer(alex).result())

解决方法

const alex = {
  first: [1,2,9,8],second: [3],third: [0,1,3]
};
const gordon = {
  first: [3],second: [2,4,5,6,7,8]
}

function createPlayer(object,name) {
  let score = 0;
  return {
    add: function() {
      for (const key in object) {
        for (const item in object[key]) {
          score += object[key][item]
        }
      }
      return this; // <<<<<
    },result: function() {
      return `${name}\'s score is ${score}`
    }
  }
}
console.log(createPlayer(alex,'Alex').add().result())

,

对于名为alex的对象,您不会显示alex

您可能是这个意思

const alex = {
  Name: "Alex",first: [1,3]
};
const gordon = {
  Name: "Gordon",first: [3],8]
}

function createPlayer(object) {
  let score = 0;
  return {
    add: function() {
      for (const key in object) {
        if (key!=="Name") {
          for (const item in object[key]) {
            score += object[key][item]
          }
        }   
      }
    },result: function() {
      return `${object.Name}\'s score is ${score}`
    }
  }
}
const player1 = createPlayer(alex)
player1.add()
console.log(player1.result())

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...