[英]How to dynamically assign properties and values to an object in Javascript
I am trying to assign properties and values to an object initialized as empty.我正在尝试将属性和值分配给初始化为空的 object。 However, it keeps on prompting the Error: Cannot assign properties of undefined (setting '0' ).但是,它一直提示 Error: Cannot assign properties of undefined (setting '0' )。 Note "duplicate" is a copy of the text gotten using the map method in some code lines above.注意“重复”是在上面的某些代码行中使用 map 方法获得的文本的副本。
I am using a for loop for this assignment.我正在为此作业使用 for 循环。 The code snippet is shown below.代码片段如下所示。
//Initialise an object to hold array data
const dataStore = {};
//Note: text is an array of string
for (let i = 0; i < text.length; i++)
{
let dataStoreKeyCounter = 0;
if ((Object.hasOwn(dataStore, text[i])) !== true)
{
for (let j = 0; j < duplicate.length; j++)
{
if (text[i] == duplicate[j])
{
dataStoreKeyCounter++;
}
}
//Set the text as the a property and the counter as its value.
dataStore.text[i] = dataStoreKeyCounter;
}
}
In your code, you put dataStore.text[i]
.在您的代码中,您放置dataStore.text[i]
。 You have not declared dataStore.text
.您尚未声明dataStore.text
。 After declaring your object, do dataStore.text = {}
声明您的 object 后,执行dataStore.text = {}
Also, make sure your duplicate is created by另外,请确保您的副本是由
let duplicate = {...dataStore}
This way, an edit to the original or the duplicate will not affect the other.这样,对原件或副本的编辑不会影响另一个。
You can change the following line:您可以更改以下行:
dataStore.text[i] = dataStoreKeyCounter;
To this:对此:
dataStore[text[i]] = dataStoreKeyCounter;
This will first evaluate the value of text[i]
and then pass it into dataStore
as the key giving you the "dynamic" nature you are looking for.这将首先评估text[i]
的值,然后将其作为键传递给dataStore
,从而为您提供您正在寻找的“动态”特性。
The difference here is that when you access like this dataStore[key]
, if the key is not present in the Object, it is created.这里的区别在于,当您像这样访问dataStore[key]
时,如果密钥不存在于 Object 中,则会创建它。
Whereas, if you access dataStore.key
, if key is not present, it will return undefined
然而,如果您访问dataStore.key
,如果 key 不存在,它将返回undefined
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.