我的老師給我們上了一節課,我們必須找出在彩票中抽了多少次斧頭號碼。他給了我們一份包含前幾年所有資料的 .txt 檔案。他告訴我們構建一個函式來發現這些值。我最終得到了這個:
//Transfer the txt logs to variable 'conteudo'
try {
conteudo = fs.readFileSync("dados.txt", "utf8");
conteudo = conteudo.split("\r\n");
vezessort = 0;
} catch(erro) {
console.error(erro.message);
}
//Function created to review all the lines in the txt file
//First for loop is to split each line, making them an array
//Second loop is to compare the values 2 to 7 on each line, where contains the numbers drawn in the lottery
function vezSort(a){
for (i = 1; i < conteudo.length; i ){
conteudo[i] = conteudo[i].split(";");
for(j = 2; j < 8; j ){
if(conteudo[i][j] == a){
vezessort = 1;
}
}
}
}
//In this exercise we need to capture the input from user, and use it as a parameter on the function
a = parseInt(prompt('Digite um número: '));
r = vezSort(a);
console.log(`O número foi sorteado ${vezessort} vezes.`);
它完美地作業,最終值與他給出的期望輸出相匹配。問題是,在下一個問題中,他告訴我們為 1 到 60 之間的每個數字回圈該函式。但是我嘗試回圈的每次嘗試都會遇到以下問題conteudo[i] = conteudo[i].split(";");:我做錯了什么?(順便說一句,在本練習中,不需要用戶的輸入。)
uj5u.com熱心網友回復:
問題是您在conteudo呼叫vezSort(). 它最初是一個字串陣列,但是當您這樣做時,您將其更改為二維陣列conteudo[i] = conteudo[i].split(";");
您應該在函式外部將其轉換為二維陣列一次,vezSort()或者使用區域變數而不是修改原始陣列。
Doint it once 效率更高,這就是我展示它的方式:
try {
conteudo = fs.readFileSync("dados.txt", "utf8");
conteudo = conteudo.split("\r\n");
conteudo = conteudo.map(line => line.split(';'));
vezessort = 0;
} catch(erro) {
console.error(erro.message);
}
//Function created to review all the lines in the txt file
//First for loop is to split each line, making them an array
//Second loop is to compare the values 2 to 7 on each line, where contains the numbers drawn in the lottery
function vezSort(a){
for (i = 1; i < conteudo.length; i ){
for(j = 2; j < 8; j ){
if(conteudo[i][j] == a){
vezessort = 1;
}
}
}
}
uj5u.com熱心網友回復:
.split()將字串轉換為子字串陣列,而不是將陣列轉換為字串。為此,使用 .join().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects /陣列/加入
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/519576.html
