迭代数组

时间:2011-05-08 22:26:38

标签: javascript

{title:'Alan', hasChild:true},
{title:'Alice', hasDetail:true},
{title:'Amos'},
{title:'Alonzo'},
{title:'Brad'},
{title:'Brent'},    
{title:'Billy'},    
{title:'Brenda'},   
{title:'Callie'},
{title:'Cassie'},   
{title:'Chris'},

如何迭代数组并找出每个元素的索引和第一个字符。

4 个答案:

答案 0 :(得分:1)

for (var i = 0, len = ary.length; i < len; i++) {   
        document.write("index:" + i + " -- first character: " + ary[i].title.charAt(0));
    }

答案 1 :(得分:1)

迭代很容易:

for (var i = 0; i < yourArrayName.length; i++) {
    yourArrayName[i].title.charAt(0) // This is the first letter.
}

答案 2 :(得分:1)

你可以像普通数组一样循环它,我很确定:

for (var i = 0; i < your_array.length; i++) {
  foo(your_array[i].title[0]);
}

答案 3 :(得分:1)

如果您想使用ES5,您可以获得更多乐趣!

array.map(function(val) {
    return val.title;
}).forEach(function(title, index) {
    console.log("First character", title[0], "at index", index);
})

这将在ES3浏览器中中断。