[英]JavaScript Array not indexing properly?
var graphdata = [["A", "B", "C", "D"], [0.5, 0.25, 0.5, 0.25]];
function randomData (){
var labels = graphdata[0]
var labels2 = graphdata[1];
console.log();
return labels.map(function(labels, labels2){
console.log(labels2);
return { label: labels , value: labels2 }
});
}
labels
iterates correctly for A, B, C, D. but labels2
gets squashed to 0, 1, 2, 3, and I am not sure why. labels
正确地针对A,B,C,D进行迭代。但是, labels2
被压缩为0、1、2、3,我不确定为什么。 Right before the return labels.map()
call, if I console.log()
, I can get the properly fractions to output but after that those values disappear and I am not sure why. 就在
return labels.map()
调用之前,如果我console.log()
,我可以正确输出分数,但是之后这些值消失了,我不确定为什么。
The Array.map() takes a callback with the parameters for the current Element , current index (optional) and the original array (optional). Array.map()使用当前Element , 当前索引 (可选)和原始数组 (可选)的参数进行回调。
randomArray.map(function(currentElement, currentIndex, randomArrayAgain) { /*...*/})
You could do: 您可以这样做:
labels.map(function(label, index) {
return { label: label, value: labels2[index] }
});
map()
will iterate over labels
and in each iteration you have access to the current label and index. map()
将遍历labels
并且在每次迭代中您都可以访问当前标签和索引。 This solution works only when your arrays are sorted in the right way. 仅当以正确的方式对数组进行排序时,此解决方案才有效。
Please read the documentation of map
here . 请在这里阅读
map
文档。 The callback to the map function takes two parameters, first being each item in the list that is to be iterated over, and second the index or key of that item in the list. map函数的回调有两个参数,第一个是列表中要迭代的每个项目,第二个是列表中该项目的索引或键。 The
labels2
variable in your map callback doesn't refer to the one you created, it refers to the index of the item being mapped upon. 地图回调中的
labels2
变量不引用您创建的变量,而是引用要映射到的项的索引。 Your implementation can be written as follows and it would be the same. 您的实现可以编写如下,并且是相同的。
labels.map(function(eachLabel, key) {
console.log(key); // 0, 1, 2, 3... (label.length - 1)
return { label: eachLabel , value: key }
});
map()
doesn't work this way. map()
不能这样工作。
The second parameter to map()
is the index of the element it is currently looking at. map()
的第二个参数是它当前正在查看的元素的索引。 So each time through it sets the first parameter labels
to the element from labels
that it's currently mapping the sets labels2
to the index of labels
. 因此,每次通过
labels
时,它都会将labels
的第一个参数labels
设置为当前正在将labels
集合labels2
映射到labels
索引的元素。
Here's more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map 详情如下: https : //developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.