关于数组使用经验实例

数组使用实例

  • 指定删除数组中的多个元素
  • 数组字符串-转-数字
  • 数组与字符串-互相转换
  • 根据id获取树形结构数据中的完整路径

指定删除数组中的多个元素

举例:[ 1,2,3,4,5,6,7] 数组中删除 2,4,5,7 四个元素;

let arr1 = [ 1,2,3,4,5,6,7];
let arr2 = [2,4,5,7]; 
for(let obj of arr2){
	arr1 = arr1.filter(item => item !== obj);
}
console.log(arr1);
// 结果:[1,3,6]

数组字符串-转-数字

// 方法一
let arr = ["2","4","6","8","10","13"]
let arr2 = arr.map(item => {
	return +item
});
console.log(arr2)
// [2, 4, 6, 8, 10, 13]
// 方法二
let arr2 = ["2","4","6","8","10","13"].map(Number);
console.log(arr2)
// [2, 4, 6, 8, 10, 13]

数组与字符串-互相转换

  • 数组 字符串
// 用‘-’把数组连接成字符串
let str = [0,1,2,3,4].join('-');
console.log(str);
// 0-1-2-3-4
  • 字符串 数组
// 用逗号(,)作为分隔,把字符串转成数组
let str = "hello,wworld,hi"
let arr = str.split(',');
console.log(arr);
// ["hello", "wworld", "hi"]

根据id获取树形结构数据中的完整路径

// 数组
let arr = [{
    "id": 1,
    "name": "配套资产",
    "level": 1,
    "fullPath": "1",
    "parentId": 0,
    "children": [{
        "id": 2,
        "name": "家居家具",
        "level": 2,
        "fullPath": "1-2",
        "parentId": 1,
        "children": [{
            "id": 3,
            "name": "床",
            "level": 3,
            "fullPath": "1-2-3",
            "parentId": 2
        }, {
            "id": 26,
            "name": "书桌",
            "level": 3,
            "fullPath": "1-2-26",
            "parentId": 2
        }, {
            "id": 27,
            "name": "衣柜",
            "level": 3,
            "fullPath": "1-2-27",
            "parentId": 2
        }, {
            "id": 28,
            "name": "椅子",
            "level": 3,
            "fullPath": "1-2-28",
            "parentId": 2
        }, {
            "id": 29,
            "name": "床头柜",
            "level": 3,
            "fullPath": "1-2-29",
            "parentId": 2
        }, {
            "id": 38,
            "name": "床垫",
            "level": 3,
            "fullPath": "1-2-38",
            "parentId": 2
        }]
    }, {
        "id": 10,
        "name": "家用电器",
        "level": 2,
        "fullPath": "1-10",
        "parentId": 1,
        "children": [{
            "id": 11,
            "name": "油烟机",
            "level": 3,
            "fullPath": "1-10-11",
            "parentId": 10
        }, {
            "id": 14,
            "name": "电热水器",
            "level": 3,
            "fullPath": "1-10-14",
            "parentId": 10
        }, {
            "id": 17,
            "name": "冰箱",
            "level": 3,
            "fullPath": "1-10-17",
            "parentId": 10
        }, {
            "id": 20,
            "name": "洗衣机",
            "level": 3,
            "fullPath": "1-10-20",
            "parentId": 10
        }, {
            "id": 23,
            "name": "空调",
            "level": 3,
            "fullPath": "1-10-23",
            "parentId": 10
        }]
    }]
}]

你可能感兴趣的:(javascript)