在 JavaScript 中,可以使用数组的sort()方法来进行排序。sort()方法会按照数组元素的字符串值进行排序,因此需要传入一个比较函数来指定排序规则。
const arr = [5, 1, 3, 2, 4];
arr.sort((a, b) => a - b);
console.log(arr); // [1, 2, 3, 4, 5]
JavaScript 中的数组对象提供了filter()方法,可以根据指定条件来筛选数组元素。
const arr = [1, 2, 3, 4, 5];
const filteredArr = arr.filter(item => item % 2 === 0);
console.log(filteredArr); // [2, 4]
JavaScript 中可以使用indexOf()方法来搜索字符串中是否包含指定的子字符串。如果找到了,就返回该子字符串在原字符串中的位置,否则返回-1。
const str = "hello world";
const index = str.indexOf("world");
console.log(index); // 6
在 JavaScript 中,可以使用slice()方法来实现分页功能。slice()方法可以从数组中选取指定位置的元素,并返回一个新的数组。
const arr = [1, 2, 3, 4, 5];
const pageSize = 2;
const page = 2;
const startIndex = (page - 1) * pageSize;
const endIndex = startIndex + pageSize;
const pagedArr = arr.slice(startIndex, endIndex);
console.log(pagedArr); // [3, 4]