The variable seems right, but

Hi,

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.

Many thanks in advance!
Rain Lover

Your second example contains variable x that stores a string value.

String value can be anything, and Javascript interpreter will NOT interpret it as valid code that could be executed. If interpreters would interpret anything that might be code withing string value, we’d have a mess :slight_smile:

Question is, why do you want to store that expression in a variable and use it in the loop? Is it because you’re learning or your design imposes that you require such a feature?

Thanks for the answer! Actually I’m creating a drop-down menu in a Google gadget that lets users to switch between two loops – one of them is a loop that puts the results in an ascending order and the other one is a loop that arranges them in a reverse order. The only code difference between these loops is what you see in parentheses:
(i=0;i<=5;i++) vs. (i=5;i>=0;i–)

The problem is I’m not allowed to use a long expression as a variable in a Google gadget and that’s why I decided to define variables for them.

Any workaround?

Well, nothing imposes that you need to use 2 for loops. In the loop, you’re incrementing value of variable i. Who says you can’t decrement value of variable j in the same loop and achieve reverse effect at the same time? :slight_smile:

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.

Unless Google is parsing that JS and doing some replacement of UP_order for the string in the <EnumValue/> tag, then the for (__UP_order__) bit looks pretty dodgy. You need semicolons for a “normal” for loop, and the “in” operator for a for-in loop.

Unfortunately I know nothing about Google gadgets - only that your javascript is wrong!