先看普通模式下遍历:
const arr = [lbb易塔云建站-模板下载,web开发资源,技术博客
{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},lbb易塔云建站-模板下载,web开发资源,技术博客
{category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},lbb易塔云建站-模板下载,web开发资源,技术博客
{category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'}lbb易塔云建站-模板下载,web开发资源,技术博客
];lbb易塔云建站-模板下载,web开发资源,技术博客
const row = [];lbb易塔云建站-模板下载,web开发资源,技术博客
//使用普通forEach()方法进行遍历,可以得到item和index值。lbb易塔云建站-模板下载,web开发资源,技术博客
arr.forEach(lbb易塔云建站-模板下载,web开发资源,技术博客
(item, index) => {row.push(item.name)}lbb易塔云建站-模板下载,web开发资源,技术博客
);
使用map遍历也可以得到item和i值。
arr.map((item, i)=>{lbb易塔云建站-模板下载,web开发资源,技术博客
row.push(item.name);lbb易塔云建站-模板下载,web开发资源,技术博客
console.log(i);lbb易塔云建站-模板下载,web开发资源,技术博客
})
使用for of 方法无法得到i值。
for(let [item, i] of arr){lbb易塔云建站-模板下载,web开发资源,技术博客
row.push(item.name);lbb易塔云建站-模板下载,web开发资源,技术博客
console.log(i);// 无法得到i或报错lbb易塔云建站-模板下载,web开发资源,技术博客
}
使用for of配合创建map实例,得到的数组自己,没有任何变化。不过由此也得到了了index值。
for(let [element, index] of new Map(arr.map((item, i) => ([item, i])))){lbb易塔云建站-模板下载,web开发资源,技术博客
console.log(element, index);lbb易塔云建站-模板下载,web开发资源,技术博客
row.push(element.name)lbb易塔云建站-模板下载,web开发资源,技术博客
}
遍历这种对象数组,建议直接使用forEach。下面看下React中的使用:
const PRODUCTS = [
{category: 'Sporting Goods', price: '$49.99', stocked: true, name: 'Football'},
{category: 'Sporting Goods', price: '$9.99', stocked: true, name: 'Baseball'},
{category: 'Sporting Goods', price: '$29.99', stocked: false, name: 'Basketball'},
{category: 'Electronics', price: '$99.99', stocked: true, name: 'iPod Touch'},
{category: 'Electronics', price: '$399.99', stocked: false, name: 'iPhone 5'},
{category: 'Electronics', price: '$199.99', stocked: true, name: 'Nexus 7'}
];
class HTMLJSX extends React.Component{
render () {
const item = this.props.item;
const price = this.props.price;
return(
<li>
<span>{item}</span>
<em>{price}</em>
</li>
)
}
}
class List extends React.Component{
render () {
const rows = [];
const productLists = this.props.products;
productLists.forEach(
(item,i) => {
rows.push(
<HTMLJSX item={item.name} price={item.price} key={i}/> //两种方法都可以进行虚拟DOM的遍历
// <li key={i}>
// <span>{item.name}</span>
// <em>{item.price}</em>
// </li>
);
}
)
console.log(rows);
return(
<ul>
{/*因为rows上面返回的是虚拟机DOM,所以可以直接在JSX里渲染了。*/}
{rows}
</ul>
)
}
}
查看结果: