meltedown wrote:
Theres something very basic about javascript arrays I'm missing.
The value of unit[i].value is 17.00
and value of the qty[i].value is 5
and I put these values into an array: myarray[unit[i].value]=qty[i].value;
I accessed the qty[i].value by putting it into <div id='test2>:
document.getElementById('test2').innerHTML+=myarra y[unit[i].value];
and it says 5
so far so good.
but this is undefined:
document.getElementById('test2').innerHTML+=myarra y[17.00];
why ?
You are unintentionally setting a property directly on your array
object using a second "feature" of the square bracket notation, instead
of adding the data as an indexed item into your array.
By calling myarray[unit[i].value], you are expecting the value property
to return a number, which you want to use as an array index. However,
it returns a string, which is ambiguous in this case, since one of two
operations will occur, based on what the string contains as text.
The problem is that an array index needs to be an integer (a Number
object), but you are passing it a String object, which is sometimes
being converted to a Number, and therefore being used as an array
index, and sometimes it is kept as a string, and therefore being used
as a property name for the array object. Refer to the following
documentation for the value property:
http://msdn.microsoft.com/library/de...es/value_1.asp
Note the part where it says "sValue: String that specifies or receives
the value for the control. ". This means you were essentially executing
myarray["17.00"], although you intended to execute myarray[17.00].
To get your code working using an array index as you intend, you need
to convert the string being returned from .value into a number before
trying to use it as an array index. The simplest way to do this is the
unary + operator, although parseInt will work too.
Here's two examples using both syntaxes:
Example A:
myarray[+unit[i].value] = "foo";
Refer to the following site for details on the unary + operator:
http://www.jibbering.com/faq/faq_not....html#tcNumber
Example B:
myarray[parseInt(unit[i].value, 10)] = "foo";
The second parameter to the parseInt call is required, refer to:
http://www.jibbering.com/faq/#FAQ4_12
If you are curious about the property setting feature of javascript's
square bracket notation, you may want to read up on this shortcut for
setting properties on any object (including an array):
http://www.jibbering.com/faq/faq_not..._brackets.html
FYI: You may want to read through the FAQ for this group, from which I
have been referring to several sections:
http://www.jibbering.com/faq/