js数组的作用,或者说为什么要有数组?
作用:使用单一的变量名来存储 多个值
创建 数组的方式:
1.通过字面量:最常用,重要
var arr1 = [ ]; //创建空数组
var arr2 = [1,2,3]; //创建数组元素为1 2 3 的 数组 arr2
2. 通过 new 关键字
var arr1 = new Array(); //创建空数组
数组的常用方法:
1. 在数组末尾插入元素
1.1 添加字符串
<template> <div>数组</div> </template> <script> export default { data() { return { dataList: [1, 2, 3], } }, computed: {}, methods: { push() { // 1.往数组尾部添加字符串 this.dataList.push('4') console.log("this.dataList",this.dataList);// [1,2,3,"4"] }, }, created() { this.push() }, } </script>
1.2 添加对象---经常遇到场景,往表格里面添加对象
<template> <div>数组</div> </template> <script> export default { data() { return { dataList: [1, 2, 3], obj1: { name: 'kb', age: 41 }, } }, computed: {}, methods: { push() { // 添加对象 this.dataList.push(this.obj1) console.log('this.dataList', this.dataList) // [1,2,3,{name:'kb',age:41}] }, }, created() { this.push() }, } </script>
2. 删除数组尾部元素
<template> <div>数组</div> </template> <script> export default { data() { return { dataList: [1, 2, 3], } }, computed: {}, methods: { pop() { // 删除尾部元素 this.dataList.pop() console.log('this.dataList', this.dataList) // [1,2] }, }, created() { this.pop() }, } </script>
3.在数组头部插入元素
<template> <div>数组</div> </template> <script> export default { data() { return { dataList: [1, 2, 3], } }, computed: {}, methods: { unshift() { // 数组头部插入元素 this.dataList.unshift(0) console.log('this.dataList', this.dataList) // [0,1,2,3] }, }, created() { this.unshift() }, } </script>
4.删除数组头部 元素
<template> <div>数组</div> </template> <script> export default { data() { return { dataList: [1, 2, 3], } }, computed: {}, methods: { shift() { // 删除数组头部元素 this.dataList.shift() console.log('this.dataList', this.dataList) // [2,3] }, }, created() { this.shift() }, } </script>
5.数组拼接 concat
<template> <div>数组</div> </template> <script> export default { data() { return { dataList1: [1, 2, 3], dataList2: [444, 555, 666], } }, computed: {}, methods: { concat() { // 数组拼接: this.dataList3 = this.dataList1.concat(this.dataList2) console.log('this.dataList3', this.dataList3) // [1,2,3,444,555,666] }, }, created() { this.concat() }, } </script>
6.删除数组元素,并像数组中添加 新元素 splice(index,many,item)
<template> <div>数组</div> </template> <script> export default { data() { return { arr1: [1, 2, 3, 4, 5], } }, computed: {}, methods: { splice() { // 删除数组元素 splic(index,many,item) // index:必须,代表删除下标,从index开始;为负数时,从尾部开始删除 // many:必须,代表删除个数 // item:非必须参数 let arr2 = this.arr1.splice(1, 3) console.log('arr2', arr2) console.log('this.arr1', this.arr1) // [1,5] // splice 删除数组元素特点;会改变原来的数组 }, }, created() { this.splice() }, } </script>
7.删除数组元素 slice(start,end)
<template> <div>数组</div> </template> <script> export default { data() { return { arr1: [1, 2, 3, 4, 5], } }, computed: {}, methods: { slice() { // 删除数组元素 slic(start,end) // start: 从何处开始取 // end:从何处结束 // 包前不包后 let arr2 = this.arr1.slice(1, 3) console.log('arr2', arr2) // 返回被选定元素 [2,3] console.log('this.arr1', this.arr1) // [1,2,3,4,5] // slice 删除数组元素特点;不会改变原来的数组 }, }, created() { this.slice() }, } </script>