我不明白为什么在以下脚本中,startDate会随currentDate一起更改,但name1保持不变。
getWorkdays('01/03/2017', '05/03/2017', 'Jimmy');
function getWorkdays (startDate, endDate, name1) {
var startDate = nlapiStringToDate(startDate);
var endDate = nlapiStringToDate(endDate);
var name1 = name1;
nlapiLogExecution('DEBUG', 'Conversion of String to Date', 'startDate is now ' + startDate + ' and endDate ' + endDate + ' and the name is ' + name1);
var name2 = name1;
var currentDate = startDate;
nlapiLogExecution('DEBUG', '', 'The currentDate is'+ currentDate + ' and the startDate is ' + startDate);
while (currentDate <= endDate) { // Loop through all dates between startDate and endDate
var weekday = currentDate.getDay(); // Retrieve the weekday (in numeric format with sunday = 0) from the currentDate
if (weekday == 1 || weekday == 6){ // Perform the following loop only if weekday is a Saturday or Sunday
nlapiLogExecution('DEBUG', '', 'The weekday number is ' + weekday + ' and the name is ' + name2);
}
var name2 = 'Jose';
currentDate.setDate(currentDate.getDate() + 1); // Go to the next date
nlapiLogExecution('DEBUG', '', 'name2 is '+ name2 + ' and name1 ' + name1);
nlapiLogExecution('DEBUG', '', 'The currentDate is'+ currentDate + ' and the startDate is ' + startDate);
}
}
如何在2017年3月1日保留startDate?
答案 0 :(得分:1)
在
var currentDate = startDate;
currentDate
和startDate
变量都指向同一个Date
对象,因此对一个变量所做的更改也会影响另一个变量(两者都“看到”同一个对象)。 / p>
在
var name2 = 'Jose';
name2
变量指向一个新字符串,但这不会改变name1
指向的内容。要获得与上面相同的效果,您必须对原始字符串进行更改(这在JavaScript中是不可能的,因为字符串是不可变的)。
如何在2017年3月1日保留startDate?
您需要创建一个新的Date
对象并使用该对象初始化currentDate
。
var currentDate = nlapiStringToDate(startDate);