在循环中定义变量

时间:2016-09-10 04:57:09

标签: javascript while-loop

怎么样

while (
  stack.peek() in ops &&
  p(stack.peek()) >= 10
) {
  str += stack.pop();
}

重写所以我每次循环运行时调用.peek(),但只定义一次?

我想过

const peek = stack.peek();
while (
  peek in ops &&
  p(peek) >= 10
) {
  str += stack.pop();
}

但是由于我在while循环中用stack修改了stack.pop(),我想stack.peek()的值每次都在变化,所以我想我必须重新定义循环内的变量,但是

let peek = stack.peek();
while (
  peek in ops &&
  p(peek) >= 10
) {
  str += stack.pop();
  peek = stack.peek();
}

似乎也有点不对,所以它应该是

while (
  let peek = stack.peek() &&
  peek in ops &&
  p(peek) >= 10
) {
  str += stack.pop();
}

for (
  let peek = stack.peek();
  peek in ops && p(peek) >= 10;
  peek = stack.peek()
) {
  str += stack.pop();
}

3 个答案:

答案 0 :(得分:1)

考虑将while (true)break

一起使用
while (true) {
  const peek = stack.peek();
  if (!(peek in ops) || p(peek) < 10) break;
  str += stack.pop();
}

理论上你也可以这样做:

while (
  (peek => peek in ops && p(peek) >= 10)(stack.peek())
) {
  str += stack.pop();
}

但那很难看。它大致相当于写

function pop(stack) {
  const peek = stack.peek();
  return peek in ops && p(peek) >= 10;
}

while(pop(stack)) str += stack.pop();

for循环也不错,可以写成:

for (let peek; peek = stack.peek(), peek in ops && p(peek) >= 10; ) {
  str += stack.pop();
}

再次避免重复调用stack.peek()

答案 1 :(得分:1)

  

怎么样

while (
  stack.peek() in ops &&
  p(stack.peek()) >= 10
) {
  str += stack.pop();
}
     

重写所以我每次循环运行时调用.peek(),但只定义   它一次?

     

对不起消费者。我创建了Array.prototype.peek =()=&gt;   这[this.length - 1]。乱糟糟的做法是不好的做法。使用Array.prototype?

注意,

var stack = [1,2,3]; 
stack.peek();

使用3关键字在此处返回function

Array.prototype.peek = function() { return this[this.length - 1]}

使用箭头功能

Array.prototype.peek = () => this[this.length - 1]; stack.peek()

返回undefined

您也可以在stack.length -1循环中使用表达式while作为条件; e.g;

&#13;
&#13;
var stack = [-2, -1, 0, 1, 2, 3, 4, 5],
  n = 0;

while (stack.length - 1 && (peek = stack.pop())) {
  // do stuff
  n += (curr = peek * 10) >= 10 ? curr : n;
  delete curr;
  console.log(`peek:${peek}`);
}

console.log(`n:${n}, peek:${peek}`);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

至少,这应该有效。

var peek = stack.peek();  //Declaration (once) and initialization

while ((peek in ops) && (p(peek) >= 10))
{
  str += stack.pop();
  peek = stack.peek()    //Re-assignment after modifying stack.
}

在循环条件之前定义变量,然后将变量更新为循环内的最后一个语句。我相信你最终会得到那个解决方案。 : - )