简体   繁体   English

Javascript循环获取并显示数组中的每个第二个字符串

[英]Javascript loop to get and display every second string in array

I feel like I had this one in the bag. 我觉得我已经把这个装在袋子里了。

Basically, I will create a bill for a client, and I want to set how many installments they can make in order to pay off a service; 基本上,我将为客户创建一个帐单,并且我想设置他们可以分期付款以偿还服务的费用。 however, I would like each payment to be bi-monthly, not monthly, eg: 但是,我希望每次付款是每两个月一次,而不是每月一次,例如:

January, March, May, ... vs January, February, March ... 一月,三月,五月...与一月,二月,三月...

I have entered a value (for when the bill is created) of 2014-01-2014, and temporarily set the installment amount to 12 months, in order to test my work. 我已经输入了2014-01-2014的值(用于创建帐单的时间),并将分期付款的金额临时设置为12个月,以便测试我的工作。

The hiddenDate element value will be dynamic, along with the var called maxMonths. hiddenDate元素值以及称为maxMonths的var都是动态的。

As of now, everything looks great, but not for the months that go past "12"... Can't figure out how to reset a loop value to get this working. 到目前为止,一切看起来都很不错,但是在过去的“ 12”之后的几个月中却不是。。。还不知道如何重置循环值才能使它正常工作。

Thanks! 谢谢!

http://jsfiddle.net/scott88/oe52vz3h/2/ http://jsfiddle.net/scott88/oe52vz3h/2/

JavaScript: JavaScript的:

hiddenDate = document.getElementById("hiddenDate").value;
curDate = hiddenDate.split("-");
curMonth = parseInt(curDate[1]);
curDay = parseInt(curDate[2]);
curYear = parseInt(curDate[0]);

maxMonths = 12; // this will be a dynamic amount, set 12 for testing purposes.
months = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet", "août",     "septembre", "octobre", "novembre", "décembre"]
str = "";

moneyTotal = document.getElementById("hiddenTotal").value;
installement = parseFloat(moneyTotal / maxMonths).toFixed(2);

for (var i = curMonth; i < curMonth + maxMonths; i++) {

for (var j = 0; j < i; j++) {

    if (i < months.length) {
        increment = i + j - curMonth;
    } else {
        increment = (i + j - curMonth) - months.length;
    }

}

console.log(increment + " " + months[increment]);
month = months[increment];
str += "<li><span>$" + installement + "</span><span>postdat&eacute; &#8594;</span><span>" +     curDay + " " + month + " " + curYear + "</span></li>";
}
document.getElementById("hiddenTerms").innerHTML = str;

Change the line 换线

month = months[increment];

to be 成为

month = months[increment % 12];

Do you just want to add 2 to the current month, and wrap around if necessary? 您是否只想在当月加2,并在必要时回绕?

This looks like a problem that can be simplified with the modulus operator. 这看起来像是可以通过模数运算符简化的问题。

 curMonth = (curMonth + 2) % 12;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM