2

I am getting "Uncaught ReferenceError: i is not defined" in chrome console. What is wrong with the forEach? Am I using the forEach() function correctly here?Thank you.

<!DOCTYPE html>

<script  type="text/javascript" src="d3.min.js">

<body>


<!--Place all DOM elements here -->


<script>

//Write your code here
var data = [132,71,337,93,78,43,20,16,30,8,17,21];
//console.log(data[0]);

var donut = {key:"Glazed", value: 132};
//console.log(donut.key, donut.value);

var donuts = [
    {key:"Glazed",    value: 132},
    {key:"Jelly",     value: 71},
    {key:"Holes",     value: 337},
    {key:"Sprinkles", value: 93}
];
//console.log(donuts[1].key, donuts[1].value);
/*
for(var i = 0, len = donuts.length; i < len; i++){
    console.log(donuts[i].key, donuts[i].value);
}
*/

donuts.forEach(function(entry){
    console.log(donuts[i].key, donuts[i].value);
});

</body>

1
  • 1
    It's a simple typo/editing error; vote to close and move on. You have no i variable in your version using forEach. Use entry instead of donuts[i]. Commented Feb 12, 2016 at 7:54

2 Answers 2

8

It has to be this way:

donuts.forEach(function(entry, i){
    console.log(donuts[i].key, donuts[i].value);
});

or better without index:

donuts.forEach(function(donut){
    console.log(donut.key, donut.value);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Worth mentioning the declaration of i is commented out.
0

For each should take a parameter, if called with any object. There are different ways to use foreach. This link will be useful to you.Foreach different usage...

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.