企业官网建站 小程序开发 云逸学习园地
技术文章 许愿墙
技术文章 PHP学习 Javascript学习 DIV+CSS学习 uniapp学习 HTML学习 微信小程序、公众号知识点 VUE知识学习
您所在的位置>云逸小栈>Javascript学习>正文

javascript数组升序排序、移除指定数组元素、判断数组中是否有某个值

2024-03-12 23:12:49 浏览 2048

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

格式有点乱,自己整理看

网站开发者电话

18066742510

个人微信号
个人公众号
个人小程序
个人抖音