问题描述
我试图获得一个可以每月自动降低价格的系统,所以在12月,您支付价格的1/12,在2月,您支付价格的11/12,依此类推。
function calcTotalPrice(){
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "march";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var d = new Date();
var n = month[d.getMonth()];
// document.getElementById("demo").innerHTML = n;
var yearPrijs = 12.5;
var membership = new Array();
if (month[0]){
membership[0] = yearPrice;
}
else{
for(i = 0;i < month.length; i++){
yearPrice = yearPrice*0.9167;
membership[i] = yearPrice;
}
}
}
解决方法
好吧@jssse,我想我明白了。
let startDate = new Date();
let startPrice = 12.5;
// Copy the date/price for use in the loop
let newDate = startDate;
let newPrice = startPrice;
let monthly = [];
let totalPrice = 0;
let month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
// Uncomment either:
// To start from this month,if it is January,or January next year if not
// So,for September 2020,this will be January 2021
//let startMonth = newDate.getMonth();
//if (startMonth != 0) {
// newDate = new Date(newDate.setMonth(12));
//}
// OR:
// To start from January this year,no matter what month we are in
// so,this will be January 2020
newDate = new Date(newDate.setMonth(0));
for (let i = 0; i < 12; i++) {
newPrice = Math.round(newPrice * 100)/100;
monthly.push({"Month": month[newDate.getMonth()],"Cost": newPrice});
totalPrice += newPrice;
// create the new date/price for next month
//newPrice = newPrice - (newPrice * (1 / 12));
newPrice = newPrice - (startPrice / 12);
let m = newDate.getMonth() + 1;
newDate = new Date(newDate.setMonth(m));
}
console.table(monthly);
console.log(totalPrice);
对于这样的事情,通常最简单的方法是在电子表格中构建某些内容-获得所需的结果后,便有了可以转换为javascript代码的公式。在这种情况下,这只是每月将金额减少1/12的一种情况-但仅在处理了第一个月之后(就像在电子表格中一样-您只将公式放在第二行之后)。
通常,在输出数组时,我会使用console.table(arrayname)-但这在片段中似乎不起作用,因此我改用了console.log,因此您可能必须将代码复制到您自己的html文件以查看数组值。