es6之数组循环

114 阅读1分钟
  <select name="" id="">
        <option value="">是否已婚</option>
        <option value="0">未婚</option>
        <option value="1">已婚</option>
    </select>
    <button onclick="query()">查询</button>
    <table border="1">
        <tr>
            <th>姓名</th>
            <th>年龄</th>
            <th>是否已婚</th>
        </tr>
        
    </table>
  
 
        /* yh:0未婚 1已婚 */
        let arr = [{
            name:"张三",
            age:18,
            yh:0,
            arr01:{
                car:'宝马',
                color:'白色'
            }
        },{
            name:"李四",
            age:30,
            yh:1,
            arr01:{
                car:'奔驰',
                color:'红色'
            }
        },{
            name:"王五",
            age:28,
            yh:0,
            arr01:{
                car:'保时捷',
                color:'黄色'
            }
        },{
            name:"李丽",
            age:35,
            yh:1,
            arr01:{
                car:'法拉利',
                color:'绿色'
            }
        }];
        /* 第一次进入页面 渲染table */
        arr.forEach(r=>{
            $('table').append(`
                <tr>
                    <td>${r.name}</td>
                    <td>${r.age}</td>
                    <td>${r.yh}</td>
                </tr>
            `)
        })

        /* 点击查询的时候选择对应的数据 */
        function query(){
            let val = $('select').val();
            $('table').html(`
            <tr>
                <th>姓名</th>
                <th>年龄</th>
                <th>是否已婚</th>
            </tr>`);
            let newArr = arr.filter(r=>r.yh==val);
            console.log(newArr);
            newArr.forEach(r=>{
                $('table').append(`
                    <tr>
                        <td>${r.name}</td>
                        <td>${r.age}</td>
                        <td>${r.yh}</td>
                    </tr>
                `)
            })
        }

        /* 传统方式 */
        /* for(let i=0;i<arr.length;i++){
            console.log(arr[i].name)
        } */
        /* for in 常用于遍历对象 数组也可以 key就是数组的索引*/
        /* for(let key in arr){
            console.log(arr[key].name)
        } */
        /* es6的另一个循环的方式 */
        /* val直接就是数组的每一个值 */
        /* for(let val of arr){
            console.log(val.name);
        } */
        /* es6的forEach 不能return */
        /* r表示数组的每个值 i代表索引 */
        /* arr.forEach( (r,i)=>{
            console.log(r,i);
        }) */
        /* es6的map方法 可以帮我们返回一个新数组 */
        /* let newArr = arr.map( (r,i)=>r.arr01); */
        /* 判断内容结果的布尔值数组 r.yh==1*/
        /* 返回一个姓名的新数组 =>r.name */
        /* console.log(newArr); */
        /* 新建一个json数组 循环 返回json数组的 全是姓名的新数组  */

        /* es6的数组方法之过滤 返回一个过滤后的新数组*/
        /* 返回一个已婚人数的新数组 */
        /* let newArr = arr.filter( r => r.yh==1 );
        console.log(newArr); */