這是我的編碼。
switch(education){
case "no highschool diploma":
salary="25636";
break;
case "a high school diploma":
salary="35256";
break;
case "an Associate's degree":
salary = "41496";
break;
case "an Bachelor's degree":
salary = "59124";
break;
case "an Master's degree":
salary = "69732";
break;
case "an Professional degree":
salary = "89960";
break;
case "an Doctoral degree":
salary = "84396";
break;
}
console.log("In 2015, a person with " education " earned an average of " salary.toLocaleString("en-US") "/year.");
我想知道為什么結果
2015年,一個高中畢業的人平均年收入35256。
代替
2015年,擁有高中文憑的人平均年收入為35,256。
我哪里錯了?
uj5u.com熱心網友回復:
您的值是字串,將它們設為數字:
const stringVariable = "12345";
const numberVariable = 12345;
console.log(stringVariable.toLocaleString("en-US")); // Logs 12345
console.log(numberVariable.toLocaleString("en-US")); // Logs 12,345
uj5u.com熱心網友回復:
您正在使用字串型別,您需要先轉換為數字。
console.log("In 2015, a person with " education " earned an average of " Number(salary).toLocaleString("en-US") "/year.");
uj5u.com熱心網友回復:
這是因為salary="35256" 作為字串傳遞。嘗試更改為salary=35256,它應該可以作業
uj5u.com熱心網友回復:
不同的資料型別(例如 Number、String、Date)通常有自己的實作.toLocaleString()
因為您呼叫.toLocaleString()的是字串,所以您當前使用的是 Object 資料型別中定義的默認實作,該實作不會被覆寫。
但是,如果您想使用與數字關聯的版本。Number()您可以在呼叫之前使用將字串轉換為數字.toLocaleString()。
如果您想了解更多資訊,請閱讀:https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/toLocaleString
演示
const education = "a high school diploma";
switch(education){
case "no highschool diploma":
salary="25636";
break;
case "a high school diploma":
salary="35256";
break;
case "an Associate's degree":
salary = "41496";
break;
case "an Bachelor's degree":
salary = "59124";
break;
case "an Master's degree":
salary = "69732";
break;
case "an Professional degree":
salary = "89960";
break;
case "an Doctoral degree":
salary = "84396";
break;
}
console.log("In 2015, a person with " education " earned an average of " Number(salary).toLocaleString("en-US") "/year.");
uj5u.com熱心網友回復:
使用整數值而不是字串值
請以這種方式編碼...
const edu_salary =
{ "no highschool diploma" : 25636
, "a high school diploma" : 35256
, "an Associate's degree" : 41496
, "an Bachelor's degree" : 59124
, "an Master's degree" : 69732
, "an Professional degree" : 89960
, "an Doctoral degree" : 84396
}
let education = "a high school diploma"
console.log(`In 2015, a person with ${education} earned an average of ${edu_salary[education].toLocaleString('en-US')}/year.`)
.as-console-wrapper {max-height: 100% !important;top: 0;}
.as-console-row::after {display: none !important;}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/469212.html
標籤:javascript
下一篇:Firebase存盤承諾未解決
