最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - forEach() anonymous function not defined error - Stack Overflow

programmeradmin0浏览0评论

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 using forEach. Use entry instead of donuts[i]. – T.J. Crowder Commented Feb 12, 2016 at 7:54
Add a ment  | 

2 Answers 2

Reset to default 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);
});

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

发布评论

评论列表(0)

  1. 暂无评论