如何在if语句中返回对象值?

时间:2018-04-25 15:12:05

标签: javascript node.js

如何使if语句中的行有效?

const player1 = {
    name: "Ashley",
    color: "purple",
    isTurn: true,
    play: function() {
        if (this.isTrue) {
            return `this["name"] is now playing`;
        }
    }
};

5 个答案:

答案 0 :(得分:2)

用以下代码替换字符串:

return `${this["name"]} is now playing`;

答案 1 :(得分:0)

将属性设为isTrue或使if语句变量检查'isTurn'。

答案 2 :(得分:0)

首先,不会点击if语句,因为isTrue中的player1不是可变的。

然而:

const player1 = {
    name: "Ashley",
    color: "purple",
    isTurn: true,
    isTrue: true, // Do you need this?
    play: function() {
        if (this.isTrue) { // Or should this be "inTurn"?
            console.log(this.name + " is now playing");
            return this.name + " is now playing";
        }
    }
};

player1.play();

你可以在这里看到这个:https://jsfiddle.net/ohfu2kn6/

答案 3 :(得分:0)

我认为您在if语句中使用属性isTrue时只是指isTurn

const player1 = {
    name: "Ashley",
    color: "purple",
    isTurn: true,
    play: function () {
        if (this.isTurn) {
            return this.name + ' is now playing';
        }
    }
};

答案 4 :(得分:-1)

const player1 = {
name: "Ashley",
color: "purple",
isTurn: true,
play: function() {
    if (this.isTrue) {
        return this.name +" is now playing";
    }
  }
};