1、数组升序排序
比如:
let arr = [6,3,1,8,2,4,9,5] arr.sort((a,b)=>a-b) console.log(arr) //输出位1 2 3 4 5...
即可完成排序
2、移除数组指定的元素
//第一种: filter方法
function removeElement(arr, element) {
return arr.filter(item => item !== element);
}
//第二种 splice方法
function removeElement(arr, element) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === element) {
arr.splice(i, 1);
i--;
}
}
return arr;
}
//第三种:使用reduce方法:
function removeElement(arr, element) {
return arr.reduce((result, item) => {
if(item !== element) {
result.push(item);
}
return result;
}, []);
}3、判断数组中是否有某个值
//使用Array.prototype.includes()方法:
const array = [1, 2, 3, 4, 5];
const targetValue = 3;
const hasValue = array.includes(targetValue);
console.log(hasValue); // 输出 true
//使用Array.prototype.indexOf()方法
const array = [1, 2, 3, 4, 5];
const targetValue = 3;
const hasValue = array.indexOf(targetValue) !== -1;
console.log(hasValue); // 输出 true
// 使用Array.prototype.some()方法:
const array = [1, 2, 3, 4, 5];
const targetValue = 3;
const hasValue = array.some(value => value === targetValue);
console.log(hasValue); // 输出 true
//使用for循环遍历数组:
const array = [1, 2, 3, 4, 5];
const targetValue = 3;
let hasValue = false;
for (let i = 0; i < array.length; i++) {
if (array[i] === targetValue) {
hasValue = true;
break;
}
}
console.log(hasValue); // 输出 true格式有点乱,自己整理看