简体   繁体   English

遍历数组

[英]Iterating over an array

{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'},

How to iterate over an array and find out the index and first character of each element. 如何遍历数组并找出每个元素的索引和第一个字符。

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

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]);
}

If you want to use ES5 you can have more fun! 如果您想使用ES5,可以享受更多乐趣!

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. 这将在ES3浏览器中中断。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM