gpt4 book ai didi

javascript - 在javascript中切换意外 token

转载 作者:行者123 更新时间:2023-11-30 07:44:44 25 4
gpt4 key购买 nike

我在以下代码中发现了一个意外的标记。

        switch ( hobby ) {
case =" painting ":
message = "Van Gogh was good at that.";
break;
case =" drawing ":
message = "Hey! Van Gogh did that too.";
break;
case =" playing guitar ":
message = "Bob Dylan played guitar.";
break;
case =" sleeping in ":
message = "My favorite hobby in the winter.";
break;

default
}

有人看到我错过了什么吗?

最佳答案

您可以利用函数语义来避免从每个 casebreak:

var message = (function(){
switch (hobby) {
case 'painting': return 'Van Gogh was good at that.'
case 'drawing': return 'Hey! Van Gogh did that too.'
case 'playing guitar': return 'Bob Dylan played guitar.'
case 'sleeping in': return 'My favorite hobby in the winter.'
}
}())

不过,表达此逻辑的最佳方式可能如下所示:

var messages = {
'painting': 'Van Gogh was good at that.',
'drawing': 'Hey! Van Gogh did that too.',
'playing guitar': 'Bob Dylan played guitar.',
'sleeping in': 'My favorite hobby in the winter.'
}
var message = messages[hobby]

关于javascript - 在javascript中切换意外 token ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8965043/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com