[英]Can't get my inputs to show rows and columns in javascript
因此,我應該創建一個嵌套的“ for循環”,該循環遍歷x(列)和y(行)直至達到用戶輸入的大小,以形成某種模式並生成有趣的模式(使用x和y值進行決策),將三個用戶提供的字符放置在二維網格中。”
我主要遇到行和列的問題。 我不斷得到一列和太多行。 輸入三個字符后,它將開始打印undefined和NaN。 我不知道為什么,但是這是代碼的一部分,以及我試圖開始工作的其他注釋掉的代碼。
<html>
<head>
<title> Lab </title>
</head>
<style>
</style>
<body>
<h1> </h1>
<p id= 'myParagraph'> My Paragraph! </p>
</body>
<script>
//prompt user to enter 3 characters
var charOne = prompt('Enter a character.');
var charTwo = prompt('Enter another character.');
var charThree = prompt('Enter one last character.');
console.log(charThree);
//prompt user for pattern size
var size = prompt('I will generate a pattern for you. Give me a size.');
//check
console.log('Still going.');
//loops until number is givin
while (isNaN(size) === true){
if(isNaN(size) === true){
alert('Not a number!');
size = prompt('Give me a number.');
} else {
}
}
console.log('Outta the loop');
//nested for loop for pattern
/* for(var x = 0; x < size; x++) {
for(var y = 1; y < size; y++){
document.write(charOne,charTwo,charThree + '<br>');
}
}
*/
// console.log('Outta nested loop');
/*
var cols = [];
var rows = size;
for (var i = 0; i < rows; i++){
cols[i] = [];
}*/
/*
var iMax = size;
var jMax = size;
var f = [charOne,charTwo,charThree];
for(i = 0; i < iMax; i++) {
f[i] = [charOne,charTwo,charThree];
for(j = 0; j < jMax; j++) {
f[i][j] = 0;
document.write(charOne,charTwo,charThree + '<br>');
}
}
*/
//an arry to make a pattern
chars = [charOne, charTwo, charThree];
for(var x = 0; x < size; x++){
for(var y = 1; y < size; y++){
document.write(chars[x] + chars[y] + '<br>');
}
}
</script>
</html>
我真的不明白您要在這里實現什么(您應該給我們舉一個希望得到的結果的例子),但是我已經在循環中發現了問題:
chars = [charOne, charTwo, charThree];
for(var x = 0; x < size; x++){
for(var y = 1; y < size; y++){
// Here you take the xth and yth indexes
// of the chars Array which only has 3 entries
// document.write(chars[x] + chars[y] + '<br>');
// You could try this:
document.write(chars[0] + chars[1] + '<br>');
}
}
假設我輸入了ABC,因此chars = ['A', 'B', 'C']
,假設我輸入的size
為5,那么對chars
的訪問將如下所示:
chars[0] = 'A'
chars[1] = 'B'
chars[2] = 'C'
chars[3] = undefined
chars[4] = undefined
如您所見,這里有一個索引超出范圍錯誤。
如果我理解正確,您是否希望在網格中的每個單元格上打印字母? 如果不是,請讓我知道,如果是,這應該解決:
for(var x = 0; x < size; x++) {
for(var y = 1; y < size; y++){
document.write(charOne + charTwo + charThree + '<br>');
}
}
問題在於您的循環可能會遍歷未定義的數組元素。 例如,如果輸入數字a,b,c,並且有人輸入5作為大小,那么您可能要嘗試打印大小僅為3 [0,1,2]但要索引到的數組的值[0,1,2,3,4]。 Char [3]和Char [4]不存在。 我建議將大小作為外部for循環,並使用Char []數組(3)的大小來限制兩個內部循環。 在您的情況下,請將內部循環設置為通過char.length以避免未定義。
chars = [charOne, charTwo, charThree];
for (var z = 0; z < size; z++) {
for (var x = 0; x < chars.length; x++) {
for (var y = 1; y < chars.length; y++) {
document.write(chars[x] + chars[y] + '<br>');
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.