好的,所以我在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"
}
]
答案 0 :(得分:1)
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);
}
上面的console.log应该会显示出错的地方。
答案 1 :(得分:0)
最后,我通过使用
定义数组来“解决”这个问题new Array( 'Apple', 'Orange', 'Pear' );
遗憾的是,我无法弄清楚实际问题。