js常用数据处理方法

时间:2024-04-18 17:47:25

1.获取key:value的key---for in

//for in循环一个对象所有可枚举的属性  如果便利数组返回的是下标
const obj = {name:"11",age:14}
for(let i in obj){console.log(i)}
///name age

2.遍历数组/数组对象,获取每一项的值---for of 

let arr = [3,5,7]
for(let i of arr){console.log(i)}
// 3,5,7



const arrObj = [{name:"11",age:14},{name:"222",age:23}]
for(let i of arrObj){console.log(i)}
//{name: '11', age: 14}  {name: '222', age: 23}

3.对数组或或者数组对象某一项进行数据计算、增加、删除,不影响原数组,会得到一个新数组 ---arr.map

const array1 = [{name:1,age:12},{name:2,age:67}];
const map1 = array1.map((i) => {
  delete i.name
  return {
    ...i,
  }
});

console.log(map1);
//{ age: 12 }, Object { age: 67 }

4.找数组/数组对象中满足条件的第一个元素的所在项(一个字符或者一个对象),返回所在项---arr.find

const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element) => element > 10);
console.log(found);
//  12


const array1 = [{name:'11',age:13},{name:'22',age:18}];
const found = array1.find((i) => i.name=='11');
console.log(found);
//{ name: "11", age: 13 }

4.找数组/数组对象中满足条件的所有元素的值,并返回一个新数组---arr.filter

//数组
const words = ['spray', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word) => word.length > 6);
console.log(result);
// ["exuberant", "destruction", "present"]


//数组对象
const words =[{name:'11',age:1},{name:'ee',age:34},{name:'dd',age:34}];
const result = words.filter((word) => word.age=='34');
console.log(result);

//[{ name: "ee", age: 34 }, Object { name: "dd", age: 34 }]

5.数组/自负床是否包含某个指定值--includes

const string = "我早地方领导就是多少积分"
console.log(string.includes('领导'));
//  true

const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
// true

6.数组中符合条件的下标---indexOf 、findIndex

//indexOf-数组,无法用于数组对象
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
// 1



//findIndex-s数组
const array1 = [5, 12, 8, 130, 44];
console.log(array1.findIndex(element) => element > 13));
//  3

//findIndex--数组对象
const array1 = [{name:"11",age:12},{name:"dfd",age:34}];
console.log(array1.findIndex(i=>i.name=='11'));
// 0 

7.slice和splice

slice方法返回一个新的数组对象,不会修改原数组

statrt为开始下标,如果start为负数,则从后面开始截取,

end为结束下标,截取到结束下标的前一个,如果end不写,直接截到最后一个

splice法就地移除或者替换已存在的元素和/或添加新的元素。

暂时写到这,后面在补充