当我的一个提示在下面的代码中留空时,我试图缩短返回“NO ANSWER”的代码:
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + name + ", " + age + ", " + address + ", " + credit + ", and" + social + ".");
alert("Now the internet has all of your information. Have a nice day >:D");
但是,代码不起作用。谁能告诉我为什么?
答案 0 :(得分:2)
for
循环确实有效并按预期工作。打印或使用这些输入变量时,需要使用数组arr
。那是因为当你执行arr[i] = "NO ANSWER";
时,实际上是将数组元素设置为“NO ANSWER”,而不是原始变量。请参阅以下内容:
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + arr[0] + ", " + arr[1] + ", " + arr[2] + ", " + arr[3] + ", and" + arr[4] + ".");
alert("Now the internet has all of your information. Have a nice day >:D");
答案 1 :(得分:0)
试试这个。您似乎正在更新arr,但您没有在屏幕上打印arr。
var name = prompt("What is your name?");
var age = prompt("What is your age?");
var address = prompt("What is your email address?");
var credit = prompt("What is your credit card number?");
var social = prompt("What is your social security number?");
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (arr[i] == "") {
arr[i] = "NO ANSWER";
}
}
alert("Your information is " + arr[0] + ", " + arr[1] + ", " + arr[2] + ", " + arr[3] + ", and " + arr[4] + ".");
答案 2 :(得分:0)
我试着干运行没有地址的代码。以下代码有效。 if语句需要更改
testarr = function () {
var name = 'xxx';
var age = 10;
var address;
var credit = 252525;
var social = 564654;
var arr = [name, age, address, credit, social];
var l = arr.length;
for (var i = 0; i < l; i++) {
if (!arr[i]) {
arr[i] = "NO ANSWER";
}
}
return arr;
//alert("Your information is " + name + ", " + age + ", " + address + ", " + credit + ", and" + social + ".");
//alert("Now the internet has all of your information. Have a nice day >:D");
}
var t = new testarr();
console.log ("Your information is " + t[0] + ", " + t[1] + ", " + t[2] + ", " + t[3] + ", and" + t[4] + ".")