[英]Create Key Value Pair Array in For-Loop
I have this response from my ajax我的 ajax 收到了这个回复
and this is my configs.objects
这是我的
configs.objects
configs.objects = ['Mexico','Brazil','Spain','Italy','USA'];
(7) [19, 51, 40, 69, 15, 77, 40]
I created a for-loop我创建了一个 for 循环
var datasets = [];
for (i = 0; i < configs.objects.length; i++) {
console.log(i);
datasets[i]['borderWidth'] = 1;
datasets[i]['hoverBorderWidth'] = 2;
datasets[i]['hoverBorderColor'] = '#fff';
datasets[i]['data'] = response[i];
datasets[i]['label'] = configs.objects[i];
// debugger;
}
console.log(datasets);
I kept getting我不断得到
Uncaught TypeError: Cannot set property 'borderWidth' of undefined
未捕获的类型错误:无法设置未定义的属性“borderWidth”
Why ?为什么 ? Am I doing anything wrong ?
我做错了什么吗? I've been staring at this codes for the last 2 hours.
在过去的 2 个小时里,我一直在盯着这些代码。
I can't tell why I kept getting that error.我不知道为什么我一直收到那个错误。
datasets
is an empty array with no elements, and you never add any. datasets
是一个没有元素的空数组,你永远不会添加任何元素。 Simply ensure that the i
th element is initialized as an object fist:只需确保第
i
个元素被初始化为对象拳头:
datasets[i] = {};
You could also restructure your code a bit and instead push
object literals to datasets
for the same result:您还可以稍微重组您的代码,而是
push
对象文字push
送到datasets
以获得相同的结果:
datasets.push({
borderWidth: 1,
hoverBorderWidth: 2,
hoverBorderColor: #fff,
data: response[i],
label: configs.objects[i]
});
Before you set values, you need to initialize it to an object first:在设置值之前,您需要先将其初始化为一个对象:
datasets[i] = {};
datasets[i]['key'] = 'value';
Further reading: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer进一步阅读: https : //developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Object_initializer
var datasets = []; for (i = 0; i < configs.objects.length; i++) { let obj = {} obj['borderWidth'] = 1; obj['hoverBorderWidth'] = 2; obj['hoverBorderColor'] = '#fff'; obj['data'] = response[i]; obj['label'] = configs.objects[i]; datasets[i] = obj; // debugger; }
It's because by using datasets[i]
you're approaching it as if that object already exists to grab out of the array and modify;这是因为通过使用
datasets[i]
您正在接近它,就好像该对象已经存在以从数组中取出并进行修改; when you're really trying to store those values in that empty array as objects.当您真正尝试将这些值作为对象存储在该空数组中时。
The way you handle that is to create a variable to store those properties into then push that object to your array which can look like this.您处理该问题的方法是创建一个变量来存储这些属性,然后将该对象推送到您的数组中,该数组可能如下所示。
var datasets = [];
for(i = 0; i < configs.object.length; i++){
var dataObject = {
borderWidth: 1,
hoverBorderWidth: 2,
hoverBorderColor: '#fff',
data: response[i],
label: configs.objects[i]
};
datasets.push(dataObject);
}
console.log(datasets);
Now the datasets
variable will have objects with those properties and values which you can now index into.现在
datasets
变量将包含具有您现在可以索引的属性和值的对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.