解释:下面代码中的person是data中定义的数组变量
(1)push(),从最后添加数据
this.person.push('pusha');
(2)pop(),从最后一位删除
this.person.pop();
(3)shift(),删除数组第一位元素
this.person.shift();
(4)upshift(),从第一位添加元素,可添加多个
this.person.unshift('aaa','bbb');
(5)splice(start(起始位置),length(待操作的元素个数),items(需要替换或插入的值)),任意位置插入/删除/替换元素。其中,当items值为0时不会执行删除操作。
this.person.splice(1,0,'add1','add2');//从当前位置插入两个数据
this.person.splice(1,2); //从当前位置删除两个数据
this.person.splice(1,2,'ch','dh'); //从当前位置替换两个数据
(6)sort(),排序
this.person.sort();
(7)reverse(),将数组转置输出
this.person.reverse();
(8)Vue.set(对象,索引,替换值)
Vue.set(this.person,1,'abc');
注意:通过索引值修改数组元素,不是响应式方法
this.person[0]='adda';
//push(),从最后添加数据
this.person.push('pusha');
//pop(),从最后一位删除
this.person.pop();
//shift(),删除数组第一位元素
this.person.shift();
//upshift(),从第一位添加元素,可添加多个
this.person.unshift('aaa','bbb');
//splice(start(起始位置),length(待操作的元素个数),items(需要替换或插入的值)),任意位置插入/删除/替换元素
this.person.splice(1,0,'add1','add2');//插入
this.person.splice(1,2); //删除
this.person.splice(1,2,'ch','dh'); //替换
//sort(),排序
this.person.sort();
//reverse(),将数组转置输出
this.person.reverse();
//Vue.set(对象,索引,替换值)
Vue.set(this.person,1,'abc');
本文详细介绍了JavaScript中数组的各种操作方法,如push、pop、shift、unshift、splice、sort、reverse,以及在Vue框架下如何通过Vue.set实现响应式更新。示例代码展示了这些方法的具体用法,帮助开发者更好地理解和运用这些数组操作。
373

被折叠的 条评论
为什么被折叠?



