When command line order matters?

2019-09-21 09:19发布

I'm new to coding so apologies (and please correct me) if I use wrong terminology. I was doing the following coding challenge: Given an array with multiple values, write a function that returns a new array that only contains the maximum, minimum, and average values of the original array.

This is the code I came up with during my first attempt: First attempt

Eventually I figured out through trial and error that the problem was the location of my arrnew variable. I also fixed the average Expression and the correct algorithm is: Correct algorithm

I assumed that since the max, min, and avg were changing (is there a better term for this?), the var arrnew would pick up these new values but obviously that wasn't the case. I guess my question is when does line order matter? Or probably more specifically, are there any simple rules or principles I should be aware of to help me better understand command line coding (I dont know if this is called command line coding).

Thanks

2条回答
神经病院院长
2楼-- · 2019-09-21 10:07

It is because of the compiler, the compiler will always go from top to bottom, so always try to structure your code in an ordered way.

查看更多
Lonely孤独者°
3楼-- · 2019-09-21 10:09

When you do this:

var arrnew = [max, min, avg];

This places a copy of the contents of max, min, avg into the array. Future changes to what max, min and avg contain will not affect the array in any way.

So, if you do;

var max = 3, min = 1, avg = 2;
var arrnew = [max, min, avg];    // 3, 1, 2
max = 5;
console.log(arrnew);             // 3, 1, 2

Note, the contents of arrnew are not affected at all by subsequent changes to what max, min or avg contain. This is just how Javascript (and most languages work).

查看更多
登录 后发表回答