Javascript提示计算字符串长度

时间:2016-05-15 02:21:16

标签: javascript object prompt

我正在Codeacademy学习javascript,我正在尝试从提示输入中计算字符串长度,并为每个答案显示自定义提醒。以下是我到目前为止的情况:

var answer = prompt('What is your surname?').length;

var responses = {
answer > 5: 'Your name has fewer than five characters',
answer < 5: 'Your name has more than five characters',
defaultResponse: 'You didn\'t answer?'
}

alert(responses[answer] || responses.defaultResponse);

我应该在这里放置if语句吗?或者 Switch 会更好吗?

2 个答案:

答案 0 :(得分:0)

这是一个干净的方法:

<VirtualHost *:80>
    ServerAdmin erik@murmillosoftware.com
    ServerName murmillosoftware.com
    ServerAlias www.murmillosoftware.com
    DocumentRoot /var/www/html
    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

对于类似的事情,我不会打扰开关。

答案 1 :(得分:0)

如果你想使用一个对象来查找答案,你可以这样做

var answer = prompt('What is your surname?').length;

var responses = {
more: 'Your name has more than five characters',
less: 'Your name has fewer than five characters',
default: 'You didn\'t answer?'
}

alert(answer == 0 && responses.default || answer < 5 && responses.less || answer > 5 && responses.more);