Not able to print foobar in js 只打印 foo 和 bar
Not able to print foobar in js only prints foo and bar
- 我在学js
- 你能告诉我以下任务的代码是否正确吗...
- 我可以打印 foo 和 bar
- 但无法打印 foobar
// Looping from 1 to 100 print out the following
// If the number is divisible by 3, log X foo
// if the number is divisible by 5, log X bar
// If the number is divisible by 15, log X foobar
// Only one output per number
// Expected output:
//
// 1
// 2
// 3 foo
// 4
// 5 bar
// 6 foo
// ...
// 15 foobar
// ...
// 100 bar
for(i=1; i<=100; i++){
console.log(i);
//var str = "";
if(i%3 == 0) {
//str = "foo";
console.log("foo");
}
else if(i%5 == 0) {
console.log("bar");
}
else if(i%3 == 0 && i%5 == 0) {
console.log("foobar");
}
}
您在 15 时只得到 "foo" 的原因是因为 if (15%3 == 0)
计算结果为真,而您没有考虑任何其他情况。
将 else if(i%3 == 0 && i%5 == 0)
移到顶部 if case。
for(i=1; i<=100; i++){
console.log(i);
if(i%3 == 0 && i%5 == 0) {
console.log("foobar");
}
else if(i%5 == 0) {
console.log("bar");
}
else if(i%3 == 0) {
console.log("foo");
}
}
这就是你想要的。
您可以使用浏览器开发人员工具逐步完成 javascript 的编译器。只需按 f12 并转到脚本部分,您可以设置一个断点并查看 javascript 引擎正在做什么。
- 我在学js
- 你能告诉我以下任务的代码是否正确吗...
- 我可以打印 foo 和 bar
- 但无法打印 foobar
// Looping from 1 to 100 print out the following
// If the number is divisible by 3, log X foo
// if the number is divisible by 5, log X bar
// If the number is divisible by 15, log X foobar
// Only one output per number
// Expected output:
//
// 1
// 2
// 3 foo
// 4
// 5 bar
// 6 foo
// ...
// 15 foobar
// ...
// 100 bar
for(i=1; i<=100; i++){
console.log(i);
//var str = "";
if(i%3 == 0) {
//str = "foo";
console.log("foo");
}
else if(i%5 == 0) {
console.log("bar");
}
else if(i%3 == 0 && i%5 == 0) {
console.log("foobar");
}
}
您在 15 时只得到 "foo" 的原因是因为 if (15%3 == 0)
计算结果为真,而您没有考虑任何其他情况。
将 else if(i%3 == 0 && i%5 == 0)
移到顶部 if case。
for(i=1; i<=100; i++){
console.log(i);
if(i%3 == 0 && i%5 == 0) {
console.log("foobar");
}
else if(i%5 == 0) {
console.log("bar");
}
else if(i%3 == 0) {
console.log("foo");
}
}
这就是你想要的。
您可以使用浏览器开发人员工具逐步完成 javascript 的编译器。只需按 f12 并转到脚本部分,您可以设置一个断点并查看 javascript 引擎正在做什么。