我正在 VScode 上做一项作业实验练习,但无法通过 Mocha 测试要求之一。该测试需要“接受两个参数,一个名称和一种语言,并且语言默认为 JavaScript”。我尝试将其默认为“Javascript”值,假设它需要一个 switch 语句。这是以下要求:
describe('introductionWithLanguageOptional(name, language)', function() {
it('takes in two arguments, a name and a language, and language defaults to JavaScript', function() {
expect(introductionWithLanguageOptional("Gracie")).toEqual("Hi, my name is Gracie and I am learning to program in JavaScript.");
})
})
坦白说,我自己也很困惑。
这是我尝试过的:
function introductionWithLanguageOptional(name, language= "Javascript"){
switch (name, language) {
case(name, language) :
return `Hi, my name is ${name} and I am learning to program in ${language}.`
break;
default:
return `Hi, my name is ${name} and I am learning to program in ${language}.`
}
}
console.log(introductionWithLanguageOptional("Gracie"))
//It returns with:
Hi, my name is Gracie and I am learning to program in undefined.
您的 switch-case 基本上会检查
name
和 language
是否等于自身,这总是正确的,这使得您的 switch-case 变得多余。您的 default
的功能与您的 case
完全相同。让我们摆脱它,例如:
function introductionWithLanguageOptional(name, language= "Javascript"){
return `Hi, my name is ${name} and I am learning to program in ${language}.`
}
如果不指定,
language
的默认值就是language
将具有的值。无需手动设置。