提示JavaScript如果还有别的意外令牌 [英] Prompt JavaScript If Else Unexpected Token else

查看:110
本文介绍了提示JavaScript如果还有别的意外令牌的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Code Academy自学JavaScript,我正在尝试制作一些简单的代码,以便在提示问题时,用户回复会给出回复。

I'm teaching myself JavaScript using Code Academy and I'm trying to make some simple code so that when prompt asks a question, the user reply gives a response.

示例。

prompt says "what's your favourite colour?"

user says "blue"

response "that's the same colour as the sky!"

但是当我尝试添加不同的选项时,我收到语法错误:意外的令牌。

But when I try to add different options, I get Syntax error: unexpected token else.

我试过这样做,如果我问了一个问题,答案会收到回复,但其他任何内容都会得到答复。

I tried making it so that if I asked a question, the reply gets a response but anything else gets a response.

这是代码。

prompt("what do you want?");

if ("coke");
{console.log ("no coke, pepsi.")};
else
console.log ("pepsi only.")};

如果有人有任何想法,我将非常感激!

If anyone has any ideas, I'd be very grateful!

推荐答案

免责声明:我不为可口可乐工作。

Disclaimer: I don't work for Coca Cola.

您需要保存返回值提示符如果您想稍后使用它。此外,您还有一些应该纠正的语法错误:

You need to save the return value of prompt if you want to use it later. Also, you have some syntax errors that should be corrected:

var answer = prompt('what do you want?');

if (answer === 'coke') {
    console.log('you said coke!');
} else {
    console.log('why didn\'t you say coke!?');
}

您可以在获得更多案件时使用开关:

You could also use a switch as you get more cases:

var answer = prompt('what do you want?');

switch (answer) {
    case 'coke':
        console.log('you said coke!');
        break;
    default:
        console.log('why didn\'t you say coke!?');
        break;
}

或者一个对象,因为大多数人都喜欢这样切换:

Or an object, as most people prefer this to switch:

var answer = prompt('what do you want?');

var responses = {
    coke: 'you said coke!',
    defaultResponse: 'why didn\'t you say coke!?'
};

console.log(responses[answer] || responses.defaultResponse);

这篇关于提示JavaScript如果还有别的意外令牌的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆