gpt4 book ai didi

Javascript - 创建新对象,但不传递任何参数

转载 作者:行者123 更新时间:2023-11-30 11:53:07 25 4
gpt4 key购买 nike

Javascript 新手。 尝试创建可在各种函数之间使用的数据类型(假设 OBJECT 是我在这里想要的)定义。到目前为止,定义只是变量(没有函数等)。我遇到的问题是我想先创建它,然后再设置属性...

我想做的...是有一个定义。

// Object Definition
function resultObj = {
isValid: true,
nn_name: '',
account_name: '',
translated_name: '',
address1: '',
city: '',
state: '',
zip: '',
country: '',
formattedAddress : '',
auth_string: '',
error_text: '',
error_body: '',
error_type: ''
};

在某个时候,我将创建一个该定义的实例。

myData = new resultObj;
... do some processing here...
... set a FEW of the variables
myData.zip = '12345';

我怎样才能创建这个,这样我就不必在创建时传递所有值(或空参数)?

最佳答案

如何创建原始默认/初始对象,然后每当您必须创建另一个具有完全相同初始属性的新/独立对象时,只需将旧对象复制到新对象中?

var myData = Object.assign({}, resultObj); 

您可以使用 Object.assign创建一个精确的副本。

The Object.assign() method is used to copy the values of all enumerable own properties from one or more source objects to a target object. It will return the target object.

var resultObj = {
isValid: true,
nn_name: '',
account_name: '',
translated_name: '',
address1: '',
city: '',
state: '',
zip: '',
country: '',
formattedAddress : '',
auth_string: '',
error_text: '',
error_body: '',
error_type: ''
};

var myData = Object.assign({}, resultObj);
document.write(JSON.stringify(myData));

另见:How do I correctly clone a JavaScript object?

关于Javascript - 创建新对象,但不传递任何参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38900930/

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