Just saw a code snippet that used an array pop assignment in the while condition; was wondering if this is acceptable/good practice?

var arr = [0,1,2,3,4,5];
var current;
while (current = arr.pop())
{
  // do stuff to each element stored in current
}
有帮助吗?

解决方案

It is not necessarily wrong if the code does what it is supposed to do, however, decisions such as this can be a matter of taste or opinion in personally written code. Conversely, avoiding this particular arrangement of logic may be a requirement of an employer.

Here are the things to consider.

  1. Do you understand what the code is doing?
  2. Is anyone else expected to read the code and understand what it is doing, and will it be relatively easy for them to read and understand what the code is doing?
  3. Will the code be used as part of the development code on a project for a group or organization that implements Programming Style guidelines?

Edit

To be more specific, here are some pros and cons using the code in your example.

Pros

  • In specific use cases, such as an array which is guaranteed to contain objects or other "truthy" values, this way is concise, doubling as a conditional statement and an assignment statement.

Cons

  • If the array contains undefined, null, 0, false, NaN, "" or has "holes" in it, this way will fail.

"Holes" means when the array has a length greater than 0 and some (or all) of the elements of the array have not been assigned a value.

"Truthy" means values that do not evaluate to false ( see the cons ). Do not forget NaN or "", I almost just did.

The code in your example already contains a bug. The first element in the array will be missed. Why? The first element is zero, which when used in an assignment statement, returns the value zero, which is treated as false by the while loop, meaning the while loop stops before processing the last item on the "stack", or rather the first element in the array.

其他提示

If the intention is to process the array like a queue or a stack, wherein items are removed as they're processed, yes. This is a pretty standard approach.

In fact, you'll sometimes see this sort of loop for tree traversals where stack overflows, or the need to pause and resume, are a potential problem in the recursive solution.

许可以下: CC-BY-SA归因
scroll top