我正在创建一个用作复利计算器的网站。用户以本金、利率、年度供款、投资年限等形式输入值...然后使用这些值进行计算,然后在 <table>
中显示的程序中进行计算。 .
计算要求美元金额的类型为 number
但是在 <table>
中显示这些值时我需要将它们格式化为美元金额并且类型为 string.
我试图创建一个可以接受数字或数字数组并返回字符串或字符串数组的函数(数组部分工作正常,我无法让数字部分工作):
/**
*formatAsDollarAmount takes a number or an
array of numbers and returns them formatted as strings "$xx.xx"
*@param x a number or an array of numbers
*@return String "$xx.xx" or ["$xx.xx", "$xx.xx"]
*/
function formatAsDollarAmount(x){
if(typeof(x) == 'number')
{
x = "$" + x.toFixed(2); //Doesn't work because strings are immutable?
}
else if (Array.isArray(x)) {
for(i = 0; i < x.length; i++)
{
x[i] = "$" + x[i].toFixed(2); //toFixed(2) converts a number to a string keeping two decimal places (it also rounds properly).
}
}
else{
console.log("Error from formatAsDollarAmount()");
}
}
使用此函数的示例:
let balanceArray = [1000, 1070, 1060] //An array storing the balance of an investment year over year ($1000 in year 1, $1070 in year 2, $1060 in year 3)
let annualAddition = 100; //Contribute $100 annually
formatAsDollarAmount(balanceArray); //this statement works fine and the array will be equal to ["$1000", "$1070", "$1060"]
formatAsDollarAmount(annualAddition); //This statement does nothing
现在,我想原因formatAsDollarAmount();
不适用于 number
作为一个参数与字符串的不变性有关,但我不确定?
为什么这个函数不能使用 number
作为论据?有没有一种方法可以让一个函数同时格式化 number
s 和 array
这是我需要的方式还是我应该创建两个单独的函数?
最佳答案
您没有从函数返回。在输入为数组的情况下,使用 map 并在其回调 concat $
中使用数组元素。 map
将返回一个新数组。
function formatAsDollarAmount(x) {
if (typeof(x) == 'number') {
return "$" + x.toFixed(2);
} else if (Array.isArray(x)) {
return x.map(item => "$" + item.toFixed(2))
} else {
console.log("Error from formatAsDollarAmount()");
}
}
let balanceArray = [1000, 1070, 1060]
let annualAddition = 100;
console.log(formatAsDollarAmount(balanceArray));
console.log(formatAsDollarAmount(annualAddition));
关于javascript - 可以将数字或数字数组作为参数并返回字符串或字符串数组的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56007418/