简体   繁体   中英

using a string as the for loop expressions and condition

The following loop works:

<html>
<body>
<script type="text/javascript">
var i=0;
for (i=0;i<=5;i++)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

But the following doesn't:

<html>
<body>
<script type="text/javascript">
var i=0;
var x="i=0;i<=5;i++"
for (x)
{
document.write("The number is " + i);
document.write("<br />");
}
</script>
</body>
</html>

I'd just like to create a simple variable. Please bear with me as I'm a newbie in JavaScript and let me know what I'm missing.

Let me provide my sample Google gadget:

<?xml version="1.0" encoding="UTF-8" ?> 
<Module> 
<ModulePrefs title="Sample Gadget" /> 
<UserPref name="order" 
          display_name="Results Order" 
          default_value="i = 0; i <= 5; i++" datatype="enum"> 
<EnumValue value="i = 0; i <= 5; i++" display_value="Ascending"/> 
<EnumValue value="i = 5; i >= 0; i--" display_value="Descending"/> 
</UserPref> 
<Content type="html"><![CDATA[ 
<script type="text/javascript"> 
var i=0; 
for (__UP_order__) 
{ 
document.write("The number is " + i); 
document.write("<br />"); 
} 

</script> 
]]></Content> 
</Module>

It doesn't work because of the tags <> (they're not supported), and that's why I tried to define a variable for the EnumValue value.

When you say var x="i=0;i<=5;i++" you are creating a text string. This is not interpreted by JavaScript as you are expecting.

There is a definite difference between statements and text strings. Even though it looks to the eye like the same thing, it looks to the interpreter like a text string, like "hello" or "sdflkjsdflkjsdflj" . JavaScript is not expecting a text string as loop parameters, it is expecting the three loop control parameters/statements . If you want to have a loop which starts and ends at different points, do something like this...

var i=0;
var start=0; //you can change the start position by changing this
var end=5;   //and you can change the end also

for (i=start;i<=end;i++)
{
document.write("The number is " + i);
document.write("<br />");
}

In short: You're confusing code with data. "i=0;i<=5;i++" is data (a piece of text, a string). But when writing a for-loop you have to write initialization, condition and step as code - you cannot pass text that happens to look like the code you'd write there. (In fact, you don't want to - what should happen when the data isn't like valid code? Not to mention it's not needed - see El Ronnoco's)

Because x is a string and you cannot use for statement with a string inside. If you need to change the upper bound of a for statement you can use a variable instead the fix number 5.

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