猿问

条件语句:不确定为什么它会得到未定义的结果 (JavaScipt )

我是JavaScript的新手,我只是在学习基本的,不知道为什么只有一半的代码可以工作。


var quartet = ["abasd", "bsdfa", "ccvssw"];

console.log("quartet.length : " + quartet.length);

console.log(quartet[0]);

console.log(quartet[1]);

console.log(quartet[2]);


if (quartet.length = 1) {

    console.log("It's just a Solo");

} else if (quartet.length = 2) {

    console.log("It's just a Duo");

} else if (quartet.length = 3) {

    console.log("It's just a Trio");

} else if (quartet.length = 4) {

    console.log("Perfect, a quartet, just right");

} else {

    console.log("Either too many or nobody");

};


for (var i = 0; i <= quartet.length; i++) {

    console.log(quartet[i] + " : " + i)

};

但是,任何使此条件语句在 VS Code 内部工作的尝试都会导致


quartet.length : 3

abasd

bsdfa

ccvssw

It's just a Solo

abasd : 0

undefined : 1


月关宝盒
浏览 72回答 2
2回答

守着星空守着你

您需要使用(或,最好)进行比较;使用&nbsp;=&nbsp;将分配给四重奏长度,这将截断数组。=====所以if&nbsp;(quartet.length&nbsp;==&nbsp;1)&nbsp;{等。

萧十郎

您应该使用 而不是 来比较数字。此外,条件应为 :而不是:===for loopi < quartet.lengthi <= quartet.lengthvar quartet = ["abasd", "bsdfa", "ccvssw"];console.log("quartet.length : " + quartet.length);console.log(quartet[0]);console.log(quartet[1]);console.log(quartet[2]);if (quartet.length == 1) {&nbsp; &nbsp; console.log("It's just a Solo");} else if (quartet.length == 2) {&nbsp; &nbsp; console.log("It's just a Duo");} else if (quartet.length == 3) {&nbsp; &nbsp; console.log("It's just a Trio");} else if (quartet.length == 4) {&nbsp; &nbsp; console.log("Perfect, a quartet, just right");} else {&nbsp; &nbsp; console.log("Either too many or nobody");};for (var i = 0; i < quartet.length; i++) {&nbsp; &nbsp; console.log(quartet[i] + " : " + i)};
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答