简体   繁体   English

寻求帮助了解For循环和.forEach之间的区别

[英]Seeking Help Understanding Difference between For Loop & .forEach

I have two functions that should produce the same result.我有两个应该产生相同结果的函数。 I would like clarification as to why they do not.我想澄清他们为什么不这样做。 I'm not grasping the significant difference that must exist between for-loop and.forEach.我没有理解 for-loop 和.forEach 之间必须存在的显着差异。

I'd like to though:)我想虽然:)

//
//DEMO OBJECT WITH TWO ARRAYS
//
var myArray = {
    myList1 : [1,2,3,4],
    myList2 : [5,6,7,8]
}

//
//FUNCTION ONE: Produces the sum of myArray.myList1 as expected.
//
    var firstWay = function(){
        var sum = 0;

        for(var i = 0; i < myArray.myList2.length; i++){
            sum += myArray.myList2[i];
        }
        return sum
    };

var results2 = firstWay();
console.log(results2);



//FUNCTION TWO PRODUCES NaN
//1.) I don't know why it produced NaN.
//2.) I don't understand why this function wouldn't produce the same result as firstWay.

    var secondWay = function() {
       var sum = 0;
       myArray.myList1.forEach(function(cur){
          sum += cur.value; 
       });
       return sum;
    };

var results1 = secondWay();
console.log(results1);

Remove value from sum += cur.value so it's just sum += cur .sum += cur.value中删除 value 所以它只是sum += cur The value you need is already contained in cur .您需要的value已包含在cur中。

var secondWay = function() {
   var sum = 0;
   myArray.myList1.forEach(function(cur){
      sum += cur; 
   });
   return sum;
};

var results1 = secondWay();
console.log(results1);

Many answers just stand in the doc and might be found by googling.许多答案只是在文档中,可以通过谷歌搜索找到。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

callback打回来
Function to execute on each element. Function 在每个元素上执行。 It accepts between one and three arguments:它接受一到三个 arguments:

currentValue
The current element being processed in the array数组中正在处理的当前元素
index Optional index可选
The index currentValue in the array数组中的索引 currentValue
array Optional. array可选。 The array forEach() was called upon "数组 forEach() 被调用“

So cur in your code is the current element of your array of integers.因此,代码中的cur是整数数组的当前元素。 So it's an integer.所以它是一个 integer。 So it has no value property, it IS the value you're looking for, as pointed out in a comment.所以它没有价值属性,它是你正在寻找的价值,正如评论中指出的那样。

On the second iteration you wrongly put sum += cur.value .在第二次迭代中,您错误地输入了sum += cur.value The right way shoud be: sum += cur .正确的方法应该是: sum += cur

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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