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>
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>
Share
Improve this question
asked Feb 12, 2016 at 7:47
martinbshpmartinbshp
1,1734 gold badges25 silver badges37 bronze badges
1
-
1
It's a simple typo/editing error; vote to close and move on. You have no
i
variable in your version usingforEach
. Useentry
instead ofdonuts[i]
. – T.J. Crowder Commented Feb 12, 2016 at 7:54
2 Answers
Reset to default 8It 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);
});
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...