简体   繁体   中英

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. 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.

The second argument given to the map callback is the index of the element in the iteration.

It looks like what you want would be

return labels.map(function(label, i){
    return { label: label , value: labels2[i] }
});

The Array.map() takes a callback with the parameters for the current Element , current index (optional) and the original array (optional).

randomArray.map(function(currentElement, currentIndex, randomArrayAgain) { /*...*/})

You could do:

labels.map(function(label, index) {
    return { label: label, value: labels2[index] }
});

Explanaion

map() will iterate over labels and in each iteration you have access to the current label and index. This solution works only when your arrays are sorted in the right way.

Please read the documentation of map here . 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. 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. 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.

The second parameter to map() is the index of the element it is currently looking at. 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 .

Here's more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM