Javascript 字符串数组访问返回字符

Javascript String Array Access Returns Chars

本文关键字:返回 字符 访问 数组 字符串 Javascript      更新时间:2023-09-26

好的,所以我在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"
    }
]
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);
}

上面的控制台.log应该告诉你出了什么问题。

最后,我通过定义数组来"修复"这个问题

new Array( 'Apple', 'Orange', 'Pear' );

不幸的是,我无法弄清楚实际问题。