JS数组的基操总结

定义数组

使用new构造函数定义

   	 let arr = new Array('hello', 'world', '你好', '世界');

使用字面量方式定义(更加简洁)

		let arr = ['hello', 'world', '你好', '世界'];

 
 
 

数组的类型及类型转换

数组的类型

用typeof方法检测数组会返回Object,用instanceof和isArray方法都会告诉你这是数组:

		let arr = ['hello', 'world', '你好', '世界'];
        console.log(typeof arr);
        console.log(arr instanceof Array);
        console.log(Array.isArray(arr));

在这里插入图片描述
所以数组属于Object类型,也属于Array类型。

数组与字符串的转换

		let arr = ['hello', 'world', '你好', '世界'];
        // 数组转换为字符串方法1
        let str = arr.toString();
        // 数组转换为字符串方法2
        let str2 = String(arr);
        console.log(str, typeof str);
        console.log(str2, typeof str2);

在这里插入图片描述

		let str = 'hello, world, 你好, 世界';
        // 使用字符串的符号拆分法
        console.log(str.split(","));
        // 使用from静态方法
        console.log(Array.from(str));

在这里插入图片描述

 
 
 

查找数组元素

索引号进行查找:

		let arr = ['hello', 'world', '你好', '世界'];
		console.log(arr[0], arr[3]);

在这里插入图片描述
也可以通过索引号对数组元素进行修改:

		let arr = ['hello', 'world', '你好', '世界'];
		arr[1] = 'javascript'
		console.log(arr);

在这里插入图片描述

indexOf(从头开始查找):

返回的是要查找元素的索引号

		let arr = ['hello', 'world', '你好', '世界'];
        // 参数为要查找的元素
        console.log(arr.indexOf('world'));

在这里插入图片描述

lastIndexOf(从尾开始查找):

		let arr = ['hello', 'world', '你好', '世界', 'world'];
        // 参数为要查找的元素
        console.log(arr.lastIndexOf('world'));

在这里插入图片描述
indexOf 和 lastIndexOf 如果查找不到则返回 -1
可以有第二个参数,第二个参数为从第几号索引开始查找

includes()

找到则返回true,找不到则返回false

		let arr = ['hello', 'world', '你好', '世界'];
        // 参数为要查找的元素
        console.log(arr.includes('world'));

在这里插入图片描述

find与findIndex方法

find方法的参数是一个函数,里面的函数的参数item就是所遍历的arr的元素。

		let arr = ['hello', 'world', '你好', '世界'];
        arr.find((item) => console.log(item))

在这里插入图片描述

		let arr = ['hello', 'world', '你好', '世界'];
        let res = arr.find((item) => {
        	// 返回的元素如果存在item里,就返回该元素
            return item === '世界';
        })
        console.log(res);

在这里插入图片描述
那么这个方法有什么用呢?find方法使用与查找元素为引用类型的数组:

		let lessons = [
		{name: 'js'}, 
        { name: 'css'}, 
        { name: 'html'}
        ];
        let result = lessons.find((item) => {
          // 如果item的name属性有包含css,则返回该元素。
            return item.name === 'css';
        })
        console.log(result);

在这里插入图片描述
而findIndex则是查找该元素所在的索引号:

		let lessons = [
		{name: 'js'}, 
        { name: 'css'}, 
        { name: 'html'}
        ];
        let result = lessons.findIndex((item) => {
          // 如果item的name属性有包含css,则返回该元素。
            return item.name === 'css';
        })
        console.log(result);

在这里插入图片描述
 
 
 
 

数组添加元素

通过下标追加元素

		let arr = ['hello', 'world', '你好', '世界'];
        arr[4] = 'javascript';
        console.log(arr);
        arr[arr.length] = 'Array'
        console.log(arr);

在这里插入图片描述

push方法追加

		let arr = ['hello', 'world', '你好', '世界'];
        arr.push('javascript', 'Array');
        console.log(arr);

在这里插入图片描述

unshift在数组首位添加

		let arr = ['hello', 'world', '你好', '世界'];
        arr.unshift('javascript', 'Array')
        console.log(arr);

在这里插入图片描述

展开语法合并数组

		let arr = ['hello', 'world', '你好', '世界'];
        let array = ['芜湖', '起飞'];
        arr = [...arr, ...array];
        console.log(arr);

在这里插入图片描述

concat()合并数组

		let arr = ['hello', 'world', '你好', '世界'];
        let array = ['芜湖', '起飞'];
        let Array = ['html', 'css', 'js']
        let ARRAY = arr.concat(array, Array);
        console.log(ARRAY);

在这里插入图片描述
concat方法不会改变原来的数组,会返回一个新的数组。
 
 
 
 

删除数组

delete运算符

		let arr = ['hello', 'world', '你好', '世界'];
        delete arr[2];
        console.log(arr);
        console.log(arr[2]);
        console.log(arr.length);

在这里插入图片描述

delete方法会留下undefined的空洞,数组的长度不会改变

pop()方法删除数组最后一个元素

如果我们单独打印arr.pop()打印出被删除的值。

		let arr = ['hello', 'world', '你好', '世界'];
        console.log(arr.pop());
        console.log(arr);

在这里插入图片描述

shift()方法删除数组第一个元素

如果我们单独打印arr.shift()打印出被删除的值。

		let arr = ['hello', 'world', '你好', '世界'];
        console.log(arr.shift());
        console.log(arr);

在这里插入图片描述

splice

第一个参数是从第几个索引开始,第二个参数是要删除几个

		let arr = ['hello', 'world', '你好', '世界'];
        // 从1号索引开始,删除2个元素
        // 直接打印会打印出被删除元素的数组
        console.log(arr.splice(1, 2));
        console.log(arr);

在这里插入图片描述
splice不止有删除的功能,还有替换的功能:

		let arr = ['hello', 'world', '你好', '世界'];
        // 从1号索引开始,删除2个元素
        // 后面添加的元素会替换到被删除元素的位置上
        arr.splice(1, 2, 'html', 'css', 'javascript');
        console.log(arr);

在这里插入图片描述
 
 
 
 

数组切片slice()

第一个参数是从第几个索引开始,第二个参数是到第几个索引结束

		let arr = ['hello', 'world', '你好', '世界'];
		// 会打印出被截取的数组片段,但是不会进行删除
        console.log(arr.slice(1, 3));
        console.log(arr);

在这里插入图片描述
如果第二个参数省略,会截取第一个参数的索引号后的全部元素

		let arr = ['hello', 'world', '你好', '世界'];
		// 会打印出被截取的数组片段,但是不会进行删除
        console.log(arr.slice(1));
        console.log(arr);

在这里插入图片描述
如果没有参数,就截取所有元素

		let arr = ['hello', 'world', '你好', '世界'];
        console.log(arr.slice());

在这里插入图片描述
 
 
 
 

清空数组

方法一:将空数组赋值给原数组

		let arr = ['hello', 'world', '你好', '世界'];
        console.log(arr);
        arr = [];
        console.log(arr);

在这里插入图片描述
方法一的操作类似于深拷贝,将原数组拷贝被另一个数组变量后,原数组清空了但是另一个数组变量仍保留着数据

		let arr = ['hello', 'world', '你好', '世界'];
		// 先赋值给另一个变量
        let array = arr;
        arr = [];
        console.log(arr);
        console.log(array);

在这里插入图片描述

方法二:将数组长度设为0

		let arr = ['hello', 'world', '你好', '世界'];
        console.log(arr);
        arr.length = 0;
        console.log(arr);

在这里插入图片描述
方法二类似于浅拷贝,尽管赋值给另一个数组,一旦一个数组清空,2个都空。

		let arr = ['hello', 'world', '你好', '世界'];
        let array = arr;
        arr.length = 0;
        console.log(arr);
        console.log(array);

在这里插入图片描述
 
 
 
 

数组的排序

sort方法

		let arr = [12, 45, 23, 52, 24, 21, 92, 82];
        arr = arr.sort((a, b) => {
            // a - b 升序     b - a 降序
            return b - a;
        });
        console.log(arr);

在这里插入图片描述

		let arr = [
		{
            name: '张三',
            score: 88
        }, 
        {
            name: '李四',
            score: 78
        }, 
        {
            name: '王五',
            score: 82
        },
         {
            name: '刘六',
            score: 55
        }];
        arr = arr.sort((a, b) => {
            return a.score - b.score;
        });
        console.table(arr);

在这里插入图片描述
 
 
 
 

数组的循环

for…of

可以遍历值类型,也可以遍历引用类型

		let arr = ['hello', 'world', '你好', '世界'];
        for (let value of arr) {
            console.log(value);
        }
        
        let array = [{
            name: '张三',
            score: 88
        }, {
            name: '李四',
            score: 78
        }, {
            name: '王五',
            score: 82
        }, {
            name: '刘六',
            score: 55
        }];
        for (let val of array) {
            console.log(val);
            console.log(val.name);
        }

在这里插入图片描述
for…in 遍历的是数组的索引

		let arr = ['hello', 'world', '你好', '世界'];
        for (let key in arr) {
            console.log(key);
        }

在这里插入图片描述

forEach方法

 		let arr = ['hello', 'world', '你好', '世界'];
        arr.forEach((value) => {
            console.log(value);
        });
        
		let array = [
		{
            name: '张三',
            score: 88
        },
         {
            name: '李四',
            score: 78
        }, 
        {
            name: '王五',
            score: 82
        }, 
        {
            name: '刘六',
            score: 55
        }];
        array.forEach((value) => {
            console.log(value);
        });

在这里插入图片描述
forEach也可以直接操作DOM元素:

	<ul>
        <li>hello</li>
        <li>world</li>
    </ul>

	<script>
		let lis = document.querySelectorAll("ul li");
        lis.forEach(function(item) {
        	// 点击事件,点击背景颜色变粉
            item.addEventListener("click", function() {
                this.style.backgroundColor = 'pink'
            });
        });
    </script>

在这里插入图片描述
 
 
 
 

every与some方法

every()方法包含一个函数的参数,函数对每个数组元素指定条件,如果每个数组元素都满足条件则返回true,否则有一个不满足则返回false。

		let arr = ['hello', 'world', '你好', '世界'];
		// value为数组元素
        let status = arr.every((value) => {
        	// 如果每个元素的类型都为string,则返回true
            return typeof value === 'string';
        })
        console.log(status);

在这里插入图片描述

		let arr = ['hello', 12, 'world', '你好', '世界'];
		// value为数组元素
        let status = arr.every((value) => {
        	// 如果每个元素的类型都为string,则返回true
            return typeof value === 'string';
        })
        // 其中12不是string类型,返回false
        console.log(status);

在这里插入图片描述
every()方法可以对数组元素进行统一判断,比如成绩:

		let array = [{
            name: '张三',
            score: 88
        }, {
            name: '李四',
            score: 78
        }, {
            name: '王五',
            score: 82
        }, {
            name: '刘六',
            score: 60
        }];
        // 如果都大于60分则返回true给pass
        let pass = array.every((item) => {
            return item.score >= 60;

        });
        
        // 判断pass的布尔值返回相应的值
		console.log(pass ? "全部及格" : "有同学没及格");

在这里插入图片描述
some方法则不要求每个都符合条件,只要其中一个满足即可。

		let arr = ['hello', 12, 'world', '你好', '世界'];
		// value为数组元素
        let status = arr.some((value) => {
        	// 如果每个元素的类型都为string,则返回true
            return typeof value === 'string';
        })
        // 其中12不是string类型,返回false
        console.log(status);

在这里插入图片描述
 
 
 
 

filter过滤器

		let arr = ['hello', 12, 'world', 52,
		 { name: '张三'},'你好', '世界'];
		 
		 // 将满足条件的元素过滤掉,进新数组newArr
        let newArr = arr.filter((value) => {
            return typeof value === 'string';
        });
        
        console.log(newArr);

在这里插入图片描述
 
 
 
 

map方法与类型处理

map方法返回一个新数组,新数组的元素为map参数函数对原数组进行处理后的值。

		let arr = [12, 24, 36, 48, 52];
        let newArr = arr.map((value) => {
        	// 对原数组的每个元素*10,然后将新值返回给新数组。
            value *= 10;
            return value;
        })
        console.log(newArr);
        // 因为改变的是值类型,原数组不变
        console.log(arr);

在这里插入图片描述

		let array = [{
            name: '张三',
            score: 88
        }, {
            name: '李四',
            score: 78
        }, {
            name: '王五',
            score: 82
        }, {
            name: '刘六',
            score: 60
        }];
        let newArray = array.map((value) => {
        	// 对每个对象添加age属性,值为18
            value.age = 18;
            return value
        })
       	
        console.log(newArray);
        // 因为操作的是引用类型,value为内存地址,所以原数组也改变。
        console.log(array);

在这里插入图片描述
 
 
 
 

reduce方法

reduce内的参数为函数,函数接受2个参数,pre一开始为数组的第一个值,value为第二个值,接着pre为函数处理后的返回值,value为第三个值,依次进行。

		let arr = [12, 24, 36, 48, 52];
        arr.reduce((pre, value) => {
            console.log(pre, value);
            return value;
        });

可以看到第一次pre为第一个值12,value为第二个值24,然后返回value24;第二次打印的时候,pre为返回值24,value为第三个值36,然后返回value36;依次进行下去。
在这里插入图片描述
如果reduce接受第二个参数,比如 arr.reduce(function(){}, 0); 则pre的初始值为0,value初始值则为数组的第一个值

一个小案例,统计及格人数:

		let array = [{
            name: '张三',
            score: 88
        }, {
            name: '李四',
            score: 78
        }, {
            name: '王五',
            score: 82
        }, {
            name: '刘六',
            score: 59
        }, {
            name: '林七',
            score: 42
        }, {
            name: '赵八',
            score: 67
        }, {
            name: '郑九',
            score: 32
        }];
        // total初始值为0,value初始值为88
        // 当分数大于等于60,则total加1,然后返回total继续进行操作,
        // 直至遍历完数组
        let passTotal = array.reduce((total, value) => {
            total += value.scoe >= 60 ? 1 : 0;
            return total;
        });
         console.log(passTotal);
        });

在这里插入图片描述
 
 
 
 
 
 
 
本文章参考b站后盾人的数组视频讲解,老师讲的非常好,也收获了很多新知识,如果有兴趣的朋友可以去看看他的视频学习。

链接: 第四章 JavaScript 数组挖掘,不只是讲数组哟.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值