我是JS的新手,我有点不确定我是否正确使用了switch语句或者是否有其他错误。我不断收到意外标识符错误。谁能告诉我这里有什么问题?非常感谢你提前。
function likes(names) {
var outPut = "";
switch(names){
case (names.length === 1):
outPut = names[0] = "likes this";
break;
case (names.length === 2):
outPut = names[0] + "and" + names[1] + "like this";
break;
case (names.length === 3):
outPut = names[0] + " , " + names[1] + " and " + names[2] + " like this";
break;
case (names.length >= 4):
outPut = names[0] + names[1] + " and " names.length - 2 + "like this";
break;
default:
outPut = "no one likes this";
}
return outPut;
}
答案 0 :(得分:1)
names.length >= 4
最简洁的方法是if else
阻止。
var output = "no one likes this";
if (names.length === 1) {
outPut = names[0] = "likes this";
} else if (names.length === 2) {
outPut = names[0] + "and" + names[1] + "like this";
} else(names.length === 3):
outPut = names[0] + " , " + names[1] + " and " + names[2] + " like this";
} else if (names.length >= 4):
outPut = names[0] + names[1] + " and " + (names.length - 2) + "like this";
}
如果您仍想使用switch
,则可以稍微修改一下代码。
function likes(names) {
var outPut = "";
switch(names.length) {
case 0:
outPut = "no one likes this";
case 1:
outPut = names[0] = "likes this";
break;
case 2:
outPut = names[0] + "and" + names[1] + "like this";
break;
case 3:
outPut = names[0] + " , " + names[1] + " and " + names[2] + " like this";
break;
default:
outPut = names[0] + names[1] + " and " + (names.length - 2) + " like this";
}
return outPut;
}
答案 1 :(得分:1)
这是使用switch
:
function likes(names) {
var outPut = "";
switch (names.length) {
case 0:
outPut = "no one likes this";
break;
case 1:
outPut = names[0] + " likes this";
break;
case 2:
outPut = names[0] + " and " + names[1] + " like this";
break;
case 3:
outPut = names[0] + ", " + names[1] + " and " + names[2] + " like this";
break;
default:
outPut = names[0] + ", " + names[1] + " and " + names[names.length - 2] + " like this";
break;
}
return outPut;
}
console.log(likes(["Alice", "Bob", "Caesar"]));
但它不会显示更长阵列的所有名称。
答案 2 :(得分:0)
outPut = names[0] + names[1] + " and " names.length - 2 + "like this";
看起来你忘了“和”和names.length之间的“+”。
outPut = names[0] = "likes this";
另外我认为第二个“=”应该是一个加号。