简体   繁体   中英

Why can't I use an array as the 'specified condition' in a while loop?

So I have this code:

var myArray = [];

var value = 5;

while (myArray != [5, 4, 3, 2, 1, 0]) {

  myArray.push(value)

  value--;

  console.log(myArray);

}

when I look at the console, it goes on for an infinite loop like so..

[ 5 ]
[ 5, 4 ]
[ 5, 4, 3 ]
[ 5, 4, 3, 2 ]
[ 5, 4, 3, 2, 1 ]
[ 5, 4, 3, 2, 1, 0 ]
[ 5, 4, 3, 2, 1, 0, -1 ]
[ 5, 4, 3, 2, 1, 0, -1, -2 ]
[ 5, 4, 3, 2, 1, 0, -1, -2, -3 ]

..........

Why doesn't it stop at [5,4,3,2,1,0]? myArray = that at a point and the for loop should stop no?

Sorry for the noob question.

JavaScript does not provide built-in support for structural-equality of Arrays, but it's straightforward to implement a comparator:

function arraysEqual(a, b, orderSensitive = true) {
  // Function from https://stackoverflow.com/a/16436975/159145
  // But modified to add the `orderSensitive` option.

  if (a === b) return true;
  if (a == null || b == null) return false;
  if (a.length != b.length) return false;

  if (!orderSensitive) {
    a = Array.from(a).sort();
    b = Array.from(b).sort();
  }

  for (var i = 0; i < a.length; ++i) {
    if (a[i] !== b[i]) return false;
  }
  return true;
}

function yourCode() {
  var myArray = [];
  var value = 5;
  const finalArray = [5, 4, 3, 2, 1, 0];

  while (!arraysEqual(myArray,finalArray)) {
    myArray.push(value)
    value--;
    console.log(myArray);
  }
}

you can use the following way to fix the issue if index and values of both arrays are different

while(sortArray(myArray).toString() !== sortArray([5, 4, 3, 2, 1, 0]).toString()) {
// your code
}

sortArray(array) {
  return array.filter((a, b) => a-b)
}

If you are sure the array index and values for both arrays are same you can use

while(myArray.toString() !== [5, 4, 3, 2, 1, 0].toString()) {
// your code
}

@Christopher Barreto and welcome to StackOverflow. Good luck with your interesting question.

although @Dai right with his full answer there is much simpler built in a way to convert array to string and then compare them.

That will work for you:

var myArray = [];

var value = 5;

while (myArray.toString() != [5, 4, 3, 2, 1, 0].toString()) {

  myArray.push(value)

  value--;

  console.log(myArray);

}

Or this if you prefer:

while ((''+myArray) != ('' + [5, 4, 3, 2, 1, 0]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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