开发者

Iterating over an array

{title:'Alan', hasChild:true},
{title:'Alice', hasDetail:true},
{title:'Amos'},
{title:'Alonzo'},
{title:'Brad'},
{title:'Brent'},    
{title:'Billy'},    
{tit开发者_如何学JAVAle:'Brenda'},   
{title:'Callie'},
{title:'Cassie'},   
{title:'Chris'},

How to iterate over an array and find out the index and first character of each element.


Iterating is easy:

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


You can just loop over it like a normal array, I'm pretty sure:

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


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


If you want to use ES5 you can have more fun!

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

this will break in ES3 browsers.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜