Javascript 如何在if语句中返回对象值?
如何使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
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';
}
}
};