Reputation: 2486
Okay, so I have an array of strings on a webpage in Javascript, defined like so:
var arr = ["Apple", "Orange", "Pear"]; //this is populated by a php script prior to being sent to the client.
The problem is, when I attempt to access these items in a for loop like this:
for (var i = 0; i < arr.length; i++)
{
alert(arr[i]);
}
My output would be:
A
p
p
So, the array seems to be accessed one character at a time, which is of course not the reason I created the array.
I really cannot fathom why this would happen. Can anyone see a problem?
EDIT: The full code - it's not very nice but it's a work in progress:
var votes = {<?php foreach ($options as $o) { echo ' "'.$o['name'].'":"'.$o['votes'].'"'; if (next($options)) { echo ','; } } ?>};
var name = [<?php for ($i = 0; $i < count($options); $i++) { echo ' "'.$options[$i]['name'].'"'; if ($i < count($options)-1) { echo ','; } } ?> ];
function run(num) {
document.getElementById('out').innerHTML = '';
for (var i = 0; i < num; i++) {
if (document.getElementById(i+1).checked)
{
votes[name[i]] = (parseInt(votes[name[i]]) + 1);
document.getElementById(num+(i+1)).checked = true;
}
if (document.getElementById(num+(i+1)).checked)
{
votes[name[i]] = (parseInt(votes[name[i]]) + 1);
}
document.getElementById('out').innerHTML += name[i] + ': ' + votes[name[i]] + '<br />';
console.log('arr: ', name, 'j: ', name.length);
}
$.ajax("vote.php", {
data:votes,
});
}
Here is Options
"options" : [
{
"name" : "Children of Men",
"id" : "1",
"votes" : "0"
},
{
"name" : "City of God",
"id" : "2",
"votes" : "0"
},
{
"name" : "Hidden",
"id" : "3",
"votes" : "0"
},
{
"name" : "We Need To Talk About Kevin",
"id" : "4",
"votes" : "0"
}
]
Upvotes: 0
Views: 103
Reputation: 2486
In the end I "fixed" this problem by defining the Array with
new Array( 'Apple', 'Orange', 'Pear' );
I could not figure out the actual issue, unfortunately.
Upvotes: 0
Reputation: 6373
var arr = ['Apple', 'Orange', 'Pear'],
i,
j = arr.length;
console.log('Array?: ', arr.toString() == '[object Array]'); // edited
for (i = 0; i < j; i++) {
console.log('arr: ', arr, 'j: ', j);
}
Above console.log should show you what is wrong.
Upvotes: 1