vue关于数组常用的一些方法

在Vue中,数组的更新应该通过Vue的响应式系统来进行,以确保视图能够正确地响应这些变化。Vue提供了一些帮助我们更好地处理数组的方法,下面是一些常用的方法:

  1. vm.$set(target, propertyName/index, value):向响应式对象中添加一个属性,并确保这个属性同样是响应式的,且触发视图更新。



Vue.set(vm.items, indexOfItem, newValue);
  1. Array.prototype.push():向数组末尾添加一个或多个元素,并返回新的长度。



example1.items.push('item');
  1. Array.prototype.pop():删除数组的最后一个元素并返回该元素。



example1.items.pop();
  1. Array.prototype.shift():删除数组的第一个元素并返回该元素。



example1.items.shift();
  1. Array.prototype.unshift():向数组的开头添加一个或多个元素,并返回新的长度。



example1.items.unshift('item');
  1. Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]]):通过删除现有元素和/或添加新元素来更新数组。



example1.items.splice(indexOfItem, 1, newValue);
  1. Array.prototype.sort():对数组的元素进行排序。



example1.items.sort((a, b) => a - b);
  1. Array.prototype.reverse():颠倒数组中元素的顺序。



example1.items.reverse();
  1. Array.prototype.filter(callback[, thisArg]):创建一个新的数组,其包含通过所提供函数实现的测试的所有元素。



const newArray = example1.items.filter(item => item.length > 0);
  1. Array.prototype.concat(value1[, value2[, ...[, valueN]]]):创建一个新数组,连接两个或更多数组的元素。



const newArray = example1.items.concat(['item1', 'item2']);
  1. Array.prototype.slice(begin[, end]):返回一个新的数组对象,这个对象是一个由 begin 和 end 决定的原数组的浅拷贝,原数组不会被修改。



const newArray = example1.items.slice(0, 5);
  1. Array.prototype.map(callback[, thisArg]):创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。



const newArray = example1.items.map(item => item * 2);
  1. Array.prototype.reduce(callback[, initialValue]):对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。



const sum = example1.items.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
  1. Array.prototype.reduceRight(callback[, initialValue]):对数组中的每个元素执行一个由您提供的reducer函数(降序执行),将其结果汇总为单个返回值。



const sum = example
VUE
最后修改于:2024年08月16日 14:10

评论已关闭

推荐阅读

Vue中使用mind-map实现在线思维导图
2024年08月04日
VUE
Web前端最全Vue实现免密登录跳转的方式_vue怎么样不登录返回首页,最强技术实现
2024年08月04日
VUE
vue3 项目搭建教程(基于create-vue,vite,Vite + Vue)
2024年08月04日
VUE
Vue-颜色选择器实现方案——>Vue-Color( 实战*1+ Demo*7)
2024年08月04日
VUE
Vue项目卡顿慢加载?这些优化技巧告诉你!_vue数据多渲染卡顿
2024年08月04日
VUE
vue中的keep-alive详解与应用场景
2024年08月04日
VUE
Vue、React实现excel导出功能(三种实现方式保姆级讲解)
2024年08月04日
vue-office/docx插件实现docx文件预览
2024年08月04日
VUE
java调用js文件的两种方法(支持V8引擎)
2024年08月04日
JavaScript:解决计算精度问题/mathjs/bignumber.js/big.js/decimal.js
2024年08月04日
两周从爬虫小白变大神 _yjs_js_security_passport
2024年08月04日
JS笔记(对象、函数、数组)
2024年08月04日
Markdown.js:强大的纯JavaScript Markdown解析器
2024年08月04日
Vue项目:js模拟点击a标签下载文件并重命名,URL文件地址下载方法、请求接口下载文件方法总结。
2024年08月04日
vue 父组件怎么获取子组件里面的data数据
2024年08月04日
VUE
个人开发实现AI套壳网站快速搭建(Vue+elementUI+SpringBoot)
2024年08月04日
el-table 表格封装并改造实现单元格可编辑
2024年08月04日
none
nodejs环境下创建vue项目、SSH密钥登陆!!!
2024年08月04日
vue+quill+element-ui实现视频、图片上传及缩放保姆级教程,轻松使用富文本
2024年08月04日
【three.js】22. Imported Models导入模型
2024年08月04日