vue关于数组常用的一些方法
warning:
这篇文章距离上次修改已过271天,其中的内容可能已经有所变动。
在Vue中,数组的更新应该通过Vue的响应式系统来进行,以确保视图能够正确地响应这些变化。Vue提供了一些帮助我们更好地处理数组的方法,下面是一些常用的方法:
vm.$set(target, propertyName/index, value)
:向响应式对象中添加一个属性,并确保这个属性同样是响应式的,且触发视图更新。
Vue.set(vm.items, indexOfItem, newValue);
Array.prototype.push()
:向数组末尾添加一个或多个元素,并返回新的长度。
example1.items.push('item');
Array.prototype.pop()
:删除数组的最后一个元素并返回该元素。
example1.items.pop();
Array.prototype.shift()
:删除数组的第一个元素并返回该元素。
example1.items.shift();
Array.prototype.unshift()
:向数组的开头添加一个或多个元素,并返回新的长度。
example1.items.unshift('item');
Array.prototype.splice(start[, deleteCount[, item1[, item2[, ...]]]])
:通过删除现有元素和/或添加新元素来更新数组。
example1.items.splice(indexOfItem, 1, newValue);
Array.prototype.sort()
:对数组的元素进行排序。
example1.items.sort((a, b) => a - b);
Array.prototype.reverse()
:颠倒数组中元素的顺序。
example1.items.reverse();
Array.prototype.filter(callback[, thisArg])
:创建一个新的数组,其包含通过所提供函数实现的测试的所有元素。
const newArray = example1.items.filter(item => item.length > 0);
Array.prototype.concat(value1[, value2[, ...[, valueN]]])
:创建一个新数组,连接两个或更多数组的元素。
const newArray = example1.items.concat(['item1', 'item2']);
Array.prototype.slice(begin[, end])
:返回一个新的数组对象,这个对象是一个由 begin 和 end 决定的原数组的浅拷贝,原数组不会被修改。
const newArray = example1.items.slice(0, 5);
Array.prototype.map(callback[, thisArg])
:创建一个新数组,其结果是该数组中的每个元素是调用一次提供的函数后的返回值。
const newArray = example1.items.map(item => item * 2);
Array.prototype.reduce(callback[, initialValue])
:对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。
const sum = example1.items.reduce((accumulator, currentValue) => accumulator + currentValue, 0);
Array.prototype.reduceRight(callback[, initialValue])
:对数组中的每个元素执行一个由您提供的reducer函数(降序执行),将其结果汇总为单个返回值。
const sum = example
评论已关闭