ES6中Array对象的方法和扩展、string的扩展方法、数组的遍历

子车修平
2023-12-01

目录

一、Array对象方法

1.Array.from()

2.array.find()

3.array.findindex()

4.array.includes()

二、Array扩展

1.array.map()  

2. array.filter()

3.array.reduce()

4.array.fill()

三、string扩展

1.模板字符串的用法

2.startsWith和endsWith用法

3.repeat字符串重复次数

四、数组的遍历

1.for of遍历数组的值

2.for in 遍历索引

3.for of 遍历对象

4.forEach的用法


一、Array对象方法

1.Array.from()

将伪数组或可遍历对象转换为真正的数组(字符串,对象,类数组,set,map等)

let str = '1234';
const arr1 =Array.from(str);
console.log(arr1);//(4) ['1', '2', '3', '4']
 
 
const Arr = {
      2:'a',
      3:'b',
      length:4,
}
console.log(Array.from(Arr));// (4) [undefined, undefined, 'a', 'b']

2.array.find()

返回数组符合条件的第一个元素的值(数组与对象)

const arr = [1,2,3,4];//数组
let num = arr.find(item=>item==3);
console.log(num);//3
 
 
 
const arr1 = [    //对象
		{realname:"张三1",age:18},
		{realname:"张三2",age:17},
		{realname:"张三3",age:19},
		{realname:"张三4",age:17},
			];
console.log(arr1.find(item=>item.age==17));//age: 17 realname: "张三2"

3.array.findindex()

找出符合条件的成员的位置。

const arr = [1,2,3,4]; //数组
console.log(arr.findIndex(item=>item==4)); //3
		
const arrobj = [    //对象
		{realname:"张三1",age:18},
		{realname:"张三2",age:19},
		{realname:"张三3",age:15},
		{realname:"张三4",age:14},
			]
console.log(arrobj.findIndex(item=>item.age==19)); //1

4.array.includes()

找出某个数组是否包含给定的值。

const arr = [1,2,3,4];
console.log(arr.includes(10));//有就返回true 没有就返回false

二、Array扩展

1.array.map()  

返回新数组

const arr = [1,2,3,4];
const newarr = arr.map(item=>item+2);
console.log(newarr); //从新输出一个数组,不是改变原的数组

2. array.filter()

过滤

const arr = [1,2,3,4,5,6,7];
const newarr = arr.filter(item=> item%2==0);
console.log(newarr);

3.array.reduce()

缩减

//total:即是初始值又是返回值
//currentValue:当前值
reduce第二个参数指定初始值
const arr = [1,2,3,4,5];
let sum = arr.reduce((total,currentValue)=>{
			return total + currentValue;
},10) //可以指定初始值
console.log(sum);

4.array.fill()

填充

let arr = [1,2,3,4,5,6,7];
	arr.fill('x',1,3);
	console.log(arr);//[1, 'x', 'x', 4, 5, 6, 7]

三、string扩展

1.模板字符串的用法

function demo(){
		return "end";
			}
let es6 = "es6!";
let str = `hello,${es6},${demo()}`;
console.log(str);//hello,es6,end

2.startsWith和endsWith用法

let str = "hello,es6!";
console.log(str.startsWith("hello"));//判断某个字符串前面是否包含hello 有就为true
console.log(str.endsWith("es6!"));//判断某个字符串后面是否包含es6 有就为true

3.repeat字符串重复次数

console.log("hello".repeat(4));//hellohellohellohello

四、数组的遍历

1.for of遍历数组的值

const arr = ["a","b","c","d"];
   for(v of arr){
        console.log(v); //a,b,c,d
}

2.for in 遍历索引

const arr = ["a","b","c","d"];
    for(let k in arr){
     console.log(k); //0,1,2,3
        }

3.for of 遍历对象

   const Person={realname:'zs',age:20}
   const keys = Object.keys(Person);
   for(let k of keys){
   console.log(`k:${k}`,`v:${Person[k]}`)}; //k:realname v:zs k:age v:20

4.forEach的用法

let arr = [1,2,3,4];
	arr.forEach((item,index)=>{
	console.log(`v:${item},k:${index}`);	
			})  //v:1,k:0  v:2,k:1 v:3,k:2 v:4,k:3

例题

1.找到一组同学中考试分数及格的第一个同学并输出到页面上

<ul class="score"></ul> 
 
    <hr>
    <h1 class="username"></h1>
    <script>
        let person=[
            {realname:'张三',score:'40'},
            {realname:'李四',score:'40'},
            {realname:'王五',score:'60'},
            {realname:'赵六',score:'90'}
        ]
        let str = '';
        let userName='';
        for(i=0;i<person.length;i++){
            str = str + `<li>姓名:${person[i].realname},分数:${person[i].score}</li>`
        }
        document.querySelector('.score').innerHTML=str;
 
        userName = person.find(item=>item.score>=60)
        document.querySelector('.username').innerHTML=`姓名:${userName.realname},分数:${userName.score}`
    </script>

2.找出大于指定年龄(页面input框接收)的第一个人,并输出这个人的位置

    <ul class="age"></ul>
    <hr>
    <input type="text" placeholder="请输入年龄" value="" class="mark">
    <input type="button" value="查询" class="btn">
    <h1></h1>
    
    
    <script>
        let person=[
            {realname:'张三',age:'15'},
            {realname:'李四',age:'18'},
            {realname:'王五',age:'19'},
            {realname:'赵六',age:'20'}
        ]
        let str = '';
        for(i=0;i<person.length;i++){
            str = str + `<li>姓名:${person[i].realname},分数:${person[i].age}</li>`
        }
        document.querySelector('.age').innerHTML=str;
        btn = document.querySelector('.btn')
        
        btn.onclick=function(){
            let num;
            input=document.querySelector('.mark').value;//获得输入的值
            num = person.findIndex(item=>item.age==input)//得到下标
            if(num==-1){
            document.querySelector('h1').innerHTML='查无此人';
            }else{
                num++;
            document.querySelector('h1').innerHTML=`位置是${num}`
            }
        }
        
    </script>

3.输出一组人员信息,输出到页面信息如下(姓名,分数,是否及格60分)

    const person=[
            {realname:'zs1',age:20,score:50},
            {realname:'zs2',age:20,score:70},
            {realname:'zs3',age:20,score:80},
            {realname:'zs4',age:20,score:90}
        ]
    // 使用 for of 将内容显示在网页上
    // let arr='';
    // for(let v of person){
    //      arr =arr+ `<li>姓名:${v.realname},年龄:${v.age}</li>`
    // }
    // document.querySelector('ul').innerHTML=arr;
    let mark='';
    let newarr = person.filter(item=>{
    let rer= item.score>60?'及格':'不及格'
    mark+=`<li>姓名:${item.realname},年龄:${item.age},分数:${item.score},${rer}</li>`
    })
      document.querySelector('ul').innerHTML=mark;

 类似资料: