好的,所以我在 Javascript 的网页上有一个字符串数组,定义如下:
var arr = ["Apple", "Orange", "Pear"]; //this is populated by a php script prior to being sent to the client.
问题是,当我尝试在这样的 for 循环中访问这些项目时:
for (var i = 0; i < arr.length; i++)
{
alert(arr[i]);
}
我的输出是:
A
p
p
因此,数组似乎一次只能访问一个字符,这当然不是我创建数组的原因。
我真的无法理解为什么会发生这种情况。任何人都可以看到问题吗?
编辑:完整的代码 - 它不是很好,但它正在进行中:
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,
});
}
这是选项
"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"
}
]