gpt4 book ai didi

JavaScript:复制对象键值而不更改引用的对象键

转载 作者:行者123 更新时间:2023-11-30 00:05:31 24 4
gpt4 key购买 nike

我正在编写一个原型(prototype)函数,该函数从对象中获取日期,然后向其添加千兆秒(100 亿秒)。这是我的代码:

var Gigasecond = function(userDate){
this.userDate = userDate;
}

Gigasecond.prototype.date = function(){
var gigaDate = this.userDate;
var gigaSecond = Math.pow(10, 9);

console.log("This is the first console log: " + this.userDate);

//adding the billion seconds to the date
gigaDate.setFullYear(gigaDate.getFullYear() + Math.floor(gigaSecond / 31536000));
gigaDate.setDate(gigaDate.getDate() + Math.floor((gigaSecond % 31536000) / 86400));
gigaDate.setHours(gigaDate.getHours() + Math.floor(((gigaSecond % 31536000) % 86400) / 3600));
gigaDate.setMinutes(gigaDate.getMinutes() + Math.floor((((gigaSecond % 31536000) % 86400) % 3600) / 60));
gigaDate.setSeconds(gigaDate.getSeconds() + (((gigaSecond % 31536000) % 86400) % 3600) % 60);

console.log("this should equal the first console log: " + this.userDate);
}

this.userDate 中输入的日期是 2015 年 9 月 13 日星期日 18:00。对于函数的另一部分,我想保持 this.userDate 完好无损。问题是,当我更改 gigaDate 时,它也会更改 this.userDate。这是控制台输出:

这是第一个控制台日志:Sun Sep 13 2015 18:00:00 GMT-0600 (MDT)
这应该等于第一个控制台日志:Thu May 30 2047 19:46:40 GMT-0600 (MDT)

有什么提示吗?

最佳答案

您想创建一个新的日期对象,而不是简单地将一个对象分配给另一个对象。

var Gigasecond = function(userDate){
this.userDate = userDate;
}

Gigasecond.prototype.date = function(){
var gigaDate = new Date(this.userDate);
var gigaSecond = Math.pow(10, 9);

console.log("This is the first console log: " + this.userDate);

//adding the billion seconds to the date
gigaDate.setFullYear(gigaDate.getFullYear() + Math.floor(gigaSecond / 31536000));
gigaDate.setDate(gigaDate.getDate() + Math.floor((gigaSecond % 31536000) / 86400));
gigaDate.setHours(gigaDate.getHours() + Math.floor(((gigaSecond % 31536000) % 86400) / 3600));
gigaDate.setMinutes(gigaDate.getMinutes() + Math.floor((((gigaSecond % 31536000) % 86400) % 3600) / 60));
gigaDate.setSeconds(gigaDate.getSeconds() + (((gigaSecond % 31536000) % 86400) % 3600) % 60);

console.log("this should equal the first console log: " + this.userDate);
console.log("this should equal the new date gigaDate: " + gigaDate);
}

现在为我输出以下内容:

这是第一个控制台日志:Mon Aug 01 2016 11:43:57 GMT+1000(澳大利亚东部标准时间)

这应该等于第一个控制台日志:Mon Aug 01 2016 11:43:57 GMT+1000(澳大利亚东部标准时间)

这应该等于新日期 gigaDate:2048 年 4 月 16 日星期四 13:30:37 GMT+1000(澳大利亚东部标准时间)

关于JavaScript:复制对象键值而不更改引用的对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38689922/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com