【问题标题】:Is there a way to determine rather my object method is a function or not有没有办法确定我的对象方法是不是一个函数
【发布时间】:2019-09-12 06:36:16
【问题描述】:

我有一个函数,它遍历对象数组并返回一个模板文字,该模板文字获取一个属性值(名称)以及一个作为函数方法的属性值(这是 .move / 他们将采取多少步) .move 方法使用 math.random 选择随机数的步骤并返回该值。但是,在某些对象中,移动属性被定义为整数,例如 1 或 2,而不是随机数。

有没有办法更改我的fitnessTest 函数,使其同时接受.move().move

我尝试在我的 while 语句中使用 if else 语句

while (steps <= 20) {
  if (typeof arrayObject == function) {
    steps += arrayObject[i].move();
    turns++;
  } else
    steps += arrayObject[i].move;
    turns++;

它返回具有正确定义为整数的 .move 值的对象,但不返回具有 .move() 的对象的随机数。

function fitnessTest(arrayObject){
  let turnsArray = [];
  for (i = 0; i < arrayObject.length; i++){
    let steps = 0;
    let turns = 0;
    while (steps <= 20){
      steps += arrayObject[i].move();
      turns++;
    } turnsArray.push(`${arrayObject[i].name} took ${turns} turns to take 20 steps.` );
  }      return turnsArray;
}

现在,该函数将遍历具有.move() 作为生成随机数并返回正确字符串的函数的对象数组,但是将 .move 设置为整数的对象只会给我一个

arrayObject[i].move 的类型错误不是函数

【问题讨论】:

  • typeof arrayObject == function 应该是typeof arrayObject[i].move == function
  • typeof arrayObject 会给你arrayObject 的类型...arrayObject[i].move 显然与arrayObject 的类型不同

标签: javascript object methods


【解决方案1】:

1.typeof返回一个字符串值,你需要和一个JavaScript类型的字符串进行比较。

2。 您应该测试arrayObject 的单个项目的属性move 是否是一个函数,而不是arrayObject 本身:

typeof arrayObject[i].move == 'function'

【讨论】:

  • 这应该是一条评论。请等到您有足够的权限发表评论
【解决方案2】:

检查typeof 数组元素而不是数组变量。

var arr = [ { move: 10}, {move: function () {}} ];
console.log(typeof arr) // object
console.log(typeof arr[0].move) // number
console.log(typeof arr[1].move) // function

将您的代码更改为:

while (steps <= 20) {
  if (typeof arrayObject[i].move === "function") {
    steps += arrayObject[i].move();
    turns++;
  } else   if (typeof arrayObject[i].move === "number")
    steps += arrayObject[i].move;
    turns++

【讨论】:

    【解决方案3】:

    typeof 为您提供一个字符串,因此您需要使用"" 将其等同于一个字符串。还要比较 move 属性而不是对象本身。

    您可以根据自己的目的使用三元运算符,并且可以拥有更优雅的代码。

    while (steps <= 20) {
      steps += typeof arrayObject[i].move === "function" ? arrayObject[i].move() : arrayObject[i].move;
      turns++;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-07-07
      • 1970-01-01
      • 2020-10-21
      • 1970-01-01
      • 2022-11-22
      • 2015-03-05
      相关资源
      最近更新 更多