简体   繁体   English

为什么不能为变量分配for循环?

[英]Why can't I assign for loop to a variable?

So I am just wondering why the following code dosen't work. 所以我只是想知道为什么以下代码不起作用。 I am looking for a similar strategy to put the for loop in a variable. 我正在寻找一种类似的策略来将for循环放入变量中。

var whatever = for (i=1;i<6;i++) {
console.log(i)
};

Thanks! 谢谢!

Because a for loop is a statement and in JavaScript statements don't have values. 因为for循环是一条语句 ,而JavaScript语句中没有值。 It's simply not something provided for in the syntax and semantics of the language. 这根本不是语言的语法和语义所提供的。

In some languages, every statement is treated as an expression (Erlang for example). 在某些语言中,每个语句都被视为一个表达式(例如,Erlang)。 In others, that's not the case. 在其他情况下,情况并非如此。 JavaScript is in the latter category. JavaScript在后一类中。

It's kind-of like asking why horses have long stringy tails and no wings. 这有点像问为什么马的尾巴很长而没有翅膀。

edit — look into things like the Underscore library or the "modern" add-ons to the Array prototype for "map" and "reduce" and "forEach" functionality. 编辑 -研究Underscore库或Array原型的“现代”附加组件,以实现“地图”,“减少”和“ forEach”功能。 Those allow iterative operations in an expression evaluation context (at a cost, of course). 这些允许在表达式评估上下文中进行迭代运算(当然需要付出一定的代价)。

I suppose what you look for is function : 我想你要找的是功能

var whatever = function(min, max) {
  for (var i = min; i < max;  ++i) {
    console.log(i);
  }
}

... and later ... ... 然后 ...

whatever(1, 6);

This approach allows you to encapsulate the loop (or any other code, even declaring another functions) within a variable. 这种方法允许您循环(或任何其他代码,甚至声明其他函数) 封装在一个变量中。

Your issue is that for loops do not return values. 您的问题是for循环不返回值。 You could construct an array with enough elements to hold all the iterations of your loop, then assign to it within the loop: 您可以构造一个数组,该数组具有足够的元素来容纳循环的所有迭代,然后在循环内分配给它:

arry[j++] = i;

You can do this, but it seems that you might want to check out anonymous functions. 您可以执行此操作,但似乎您可能想签出匿名函数。 With an anonymous function you could do this: 使用匿名函数,您可以执行以下操作:

var whatever = function(){
 for (var i=1;i<6;i++) {
  console.log(i);
 }
};

and then 接着

whatever(); //runs console.log(i) i times.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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