【JS】JavaScript数组、对象常用的方法(持续更新)

gengboxb 3.9K 0

对象:

遍历对象for..in

var obj = {a:1, b:2, c:3};
    
for (var prop in obj) {
  console.log("obj." + prop + " = " + obj[prop]);
}
// 输出:
// "obj.a = 1"
// "obj.b = 2"
// "obj.c = 3"

类数组对象Object.keys

// 类数组对象
var obj = { 1: 'a', 2: 'b', 3: 'c' };
console.log(Object.keys(obj)); // ['1', '2', '3']
console.log(Object.keys(obj)[0]); // "1"
// 类数组对象-随机下标 
var anObj = { 111: 'a', 3: 'b', 8: 'c' }; 
console.log(Object.keys(anObj)); // ['3', '8', '111']
console.log(Object.keys(anObj)[0]); // "3"

Object.assign( )合并对象

var a={a:'jspang'};
var b={b:'对象合并'};
var c={c:'web'};

let d=Object.assign(a,b,c)
console.log(d); // {a: "jspang", b: "对象合并", c: "web"}

解构合并对象

let a={a:'jspang'}; 
let b={b:'对象合并'};

let obj = {...a,...b};
console.log(obj) // {a: 'jspang', b: '对象合并'}

Object.assign( )对象赋值

如果对象里属性名相同,会被覆盖

var obj = {name: 123,age: 20};
Object.assign(obj,{sex: '男'});
console.log(obj); //  {name: 123,age: 20,sex: "男"}

Object.assign(obj,{sex: '女'});
console.log(obj); //  {name: 123,age: 20,sex: "女"}

删除对象的空值字段

const reqData = {data:1,name: '',age:null}
for (const key in reqData) {
  if (reqData[key] === '' || reqData[key] === undefined || reqData[key] === null) {
      delete reqData[key]
  }
}
console.log(reqData); // {data:1}

判断对象中是否有某属性的常用方法

1、obj.hasOwnProperty('a')
2、obj.keys(obj).includes('a')

数组:

数组合并

const arr3 = ['a', 'b'];
const arr4 = ['c'];
const arr5 = ['d', 'e'];

// ES5 的合并数组
arr1.concat(arr4, arr5);
// [ 'a', 'b', 'c', 'd', 'e' ]

// ES6 的合并数组
[...arr3, ...arr4, ...arr5]
// [ 'a', 'b', 'c', 'd', 'e' ]

遍历数组for..of

可以随时使用brack;

let iterableArr = [10, 20, 30];
for (let value of iterableArr ) {
    value += 2;
    console.log(value);
}
// 12
// 22
// 32

let iterableArr2 = [10, 20, 30]; 
for (let value of iterableArr2) { 
    value += 2; 
    console.log(value);
    if(value === 12){ 
      break; 
    }
 }

// 12

Array.prototype.slice.call() 将伪数组转换为真数组

Array.prototype.slice.call(arguments,0) ;

call让arguments具有slice()方法,不然直接调用会报错

var a={length:2,0:'first',1:'second'};
console.log(Array.prototype.slice.call(a,1));// ["second"],调用数组的slice(0);

克隆数组

const arr1 = [1, 2];
const arr2 = [...arr1];
console.log(arr2); // [1, 2];

深度克隆数组

this.resList  = ["fd_COLUMNNAME": '没被改变'];
const copyColRes = JSON.parse(JSON.stringify(this.resList));
this.$set(this.resList[0], 'fd_COLUMNNAME', '改变');
console.log(copyColRes); // ["fd_COLUMNNAME": '没被改变']

将字符串转为真正的数组

const strArr = [...'helloworld'];
// ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"];

splice数组赋值

var arr = [0,1];
var arr2 = [3];

arr.splice(0,0,...arr2);
console.log(arr); // [3, 0, 1]

includes判断数组是否包含某个东西

let arr = ['a', 'b', 'c'];
console.log(arr.includes(1)); // false

修改数组中对象的属性名

/**
 *  把[{ id: 1 }, { id: 2 }] 转为 [{ adsid: 1 }, { adsid: 2 }]
 */
const arr = [{ id: 1 }, { id: 2 }];
const hasAdsArr = [];
 
//赋值克隆对象
function cloneObjectFn(obj) { // 对象复制
    return JSON.parse(JSON.stringify(obj))
}
 
for (let i = 0; i < arr.length; i++) {
    // 将数组中的每一项的id属性改成adsid
    let objCopy = cloneObjectFn(arr[i]);
    objCopy.adsid = objCopy.id;
    delete objCopy.id;
    hasAdsArr.push(objCopy);
}
 
console.log(hasAdsArr); // [{ adsid: 1 }, { adsid: 2 }]

数组降维

// 将[1, [[2], [3, [4]], 5],6] 变成 [1,2,3,4,5,6]
const flattenDeep = (arr) => Array.isArray(arr)
  ? arr.reduce( (a, b) => [...a, ...flattenDeep(b)] , [])
  : [arr]

flattenDeep([1, [[2], [3, [4]], 5],6])

两个数组对比,相同的删除,并输出第二个数组剩下的内容

let arr1 = ["11001","11038","11054"];
let arr2 = ["11038","11039"];

const newArr3 = arr2.filter(item => !arr1.includes(item));  // ["11039"]

删除数组指定的元素元素,第一个参数为要删除的index

let arr = [1,2,1];
this.colTitle.splice(2, 1);
console.log(arr); // [1,2]

数组去重

let arr = [1,1,2,3,3,4,4,5]
console.log([...new Set(arr)]); // [1, 2, 3, 4, 5]

map方法原数组映射成一个新的数组

let obj = [
  {name:'小明',age:16,sex:'男'},
  {name:'小红',age:17,sex:'女'},
  {name:'小白',age:18,sex:'女'},
]

let arr = obj.map((item)=>item.name)
console.log(arr) // ['小明', '小红', '小白']

filter数组过滤

let obj = [
  {name:'小明',age:16,sex:'男'},
  {name:'小红',age:17,sex:'女'},
  {name:'小白',age:18,sex:'女'},
]

// 过滤获取只有16岁的数据 
let arr = obj.filter(item=>item.age === 16) 
console.log(arr) // [{name: '小明', age: 16, sex: '男'}]

forEach() 方法遍历数组

let arr= [1, 2, 3];

arr.forEach((item) =>{
  console.log(item);
});

// 打印
// 1
// 2
// 3

判断是否为数组

// 判断是否为数组
isArrayFn = function (o) {
  return Object.prototype.toString.call(o) === '[object Array]';
};

isArrayFn([1,2.3]) // true

树状数据递归向上获取父级id

// data:树状数据
// value: 子级id
// idKey:唯一值
// childrenKey:子级数据属性
function getTreeArr(data, value, idKey = "id", childrenKey = "children") {
    let ids = [];
    let recursion = (treeData) => {
        let node;
        for (node of treeData) {
            if (node[idKey] === value) {
                return node[idKey];
            } else {
                if (node[childrenKey] && node[childrenKey].length) {
                    let id = recursion(node[childrenKey]);
                    if (id) {
                        ids.push(id);
                        return node[idKey];
                    }
                }
            }
        }
        return null;
    };
    let id = recursion(data);
    if (id) {
        ids.push(id);
    }
    return ids.reverse();
}

使用

let data = [
  {
    "id": 3,
    "name": "bbbb",
    "children": [
      {
        "id": 8,
        "name": "ggggg",
        "children": []
      }
    ]
  }, 
  {
    "id": 4,
    "name": "ccccc",
    "children": [
      {
        "id": 5,
        "name": "ddddd",
        "children": [
          {
            "id": 9,
            "name": "hhhhh",
            "children": []
          }
        ]
      }, 
      {
        "id": 6,
        "name": "eeeee",
        "children": [
          {
            "id": 7,
            "name": "ffff",
            "children": []
          }, 
          {
            "id": 10,
            "name": "jjjj",
            "children": []
          }
        ]
      }
    ]
  }
]


console.log(getTreeArr(data,10)) // [4, 6, 10]

字符串

截取字符串并不改变原字符串

let str = "0123456789";
console.log(str.substring(1,5))//"1234"

字符串分割/r/n

let str = 'one\r\ntwo\r\nthree' ;
let splitArr = str.split(/[\r\n]+/);
console.log(splitArr); // ["one", "two", "three"]

待更新...

发表评论 取消回复
表情 图片 链接 代码

分享