Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - When command line order matters?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

56.8k users

...