Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/411.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在if语句中返回对象值?_Javascript_Node.js - Fatal编程技术网

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

Javascript 如何在if语句中返回对象值?,javascript,node.js,Javascript,Node.js,如何使if语句中的行起作用 const player1 = { name: "Ashley", color: "purple", isTurn: true, play: function() { if (this.isTrue) { return `this["name"] is now playing`; } } }; 将字符串替换为以下内容: return `${this["name"]} is

如何使if语句中的行起作用

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

将字符串替换为以下内容:

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

将属性设为isTrue或使if语句变量选中“isTurn”。

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

您可以在这里看到这一点:

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

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

通过使用
返回
可能会重复。但是我怀疑你实际上是在问别的问题。你能澄清一下你期望代码做什么吗?如果你现在得到了任何错误的输出,那也是。return语句本身是完全有效的。
const player1 = {
    name: "Ashley",
    color: "purple",
    isTurn: true,
    play: function () {
        if (this.isTurn) {
            return this.name + ' is now playing';
        }
    }
};