常用js处理数据函数总结

本文详细介绍了JavaScript中类型转换、JSON与字符串互转、数组方法splice的用法、Math.random的随机数生成以及Reduce函数的应用。此外,还提供了树形结构与list结构转换的三种实现方式:递归、Map数据结构和reduce函数。
摘要由CSDN通过智能技术生成

一 、类型转换

1 转为string 字符串类型

let a = [0,1,2]
console.log(a.toString()) //输出结果 0,1,2

2 json 与字符串的互转

JSON.parse(jsonstr); //可以将json字符串转换成json对象
JSON.stringify(jsonobj); //可以将json对象转换成json对符串

3 splice的用法总结

说明:通过添加、删除、修改元素来修改数组

使用方法 array.splice(start,deleteCount,item)  

start:开始位置  deleteCount:删除的元素个数,  item 添加的元素 

4 Math.random随机数

Math.random()

可以用来生成一个0-1之间的随机数Math.random()

可以用来生成一个0-10之间的随机数(整数)Math.round(Math.random()*10)

可以用来生成一个0-X之间的随机数(整数)Math.round(Math.random()*X)

可以用来生成一个1-10之间的随机数(整数)Math.round(Math.random()*9)+1

可以用来生成一个1-X之间的随机数(整数)Math.round(Math.random()*(X-1))+1

可以用来生成一个Y-X之间的随机数(整数)Math.round(Math.random()*(X-Y))+Y  
原文链接:https://blog.csdn.net/m0_68036090/article/details/124637550

5 Reduce函数

​ reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

let 结果 = 数组.reduct(累加器, 初始化值)

// reduce 案例1:累加和
let arr = [1,2,3,4,5]

let s = arr.reduce( (sum,current,index)=>{

    return sum + current
} , 0)


console.info(s) //结果 15

//案例2:对象数组的累加和
let arr = [
    {
        name: 'jack',
        count: 10
    },
    {
        name: 'rose',
        count: 20
    }
]
let s = arr.reduce((sum,current,index)=>{
    return sum + current.count
},0);


console.info(s) //结果 30




二、js树形结构与list 结构互相转换示例

1 js 树形转list

//将JS的树形结构转换为列表可以使用递归算法来完成。下面是一个示例代码:
function treeToList(tree) {
    let list = []; // 存放最后生成的列表
    
    function traverseTree(node) {
        if (Array.isArray(node)) {
            node.forEach((childNode) => {
                traverseTree(childNode);
            });
        } else {
            list.push(node);
            
            if ('children' in node && Array.isArray(node['children'])) {
                node['children'].forEach((childNode) => {
                    traverseTree(childNode);
                });
            }
        }
    }
    
    traverseTree(tree);
    
    return list;
}
 
// 测试数据
const treeData = [
    { id: '1', name: '节点1', children: [{ id: '2', name: '子节点1' }, { id: '3', name: '子节点2' }]},
    { id: '4', name: '节点2'},
];
 
console.log(treeToList(treeData));

2 list 转树形

(1) 使用递归:

function buildTree(list, parentId = null) {
  const tree = [];
 
  for (const item of list) {
    if (item.parentId === parentId) {
      const children = buildTree(list, item.id);
      if (children.length) {
        item.children = children;
      }
      tree.push(item);
    }
  }
 
  return tree;
}
 
const list = [
  { id: 1, name: 'Node 1', parentId: null },
  { id: 2, name: 'Node 2', parentId: 1 },
  { id: 3, name: 'Node 3', parentId: 1 },
  { id: 4, name: 'Node 4', parentId: 2 },
  { id: 5, name: 'Node 5', parentId: 2 },
  { id: 6, name: 'Node 6', parentId: null },
];
 
const tree = buildTree(list);
console.log(tree);

2  使用Map数据结构

function buildTree(list) {
  const map = {};
  const tree = [];
 
  for (const item of list) {
    item.children = [];
    map[item.id] = item;
 
    const parentItem = map[item.parentId];
    if (parentItem) {
      parentItem.children.push(item);
    } else {
      tree.push(item);
    }
  }
 
  return tree;
}
 
const list = [
  { id: 1, name: 'Node 1', parentId: null },
  { id: 2, name: 'Node 2', parentId: 1 },
  { id: 3, name: 'Node 3', parentId: 1 },
  { id: 4, name: 'Node 4', parentId: 2 },
  { id: 5, name: 'Node 5', parentId: 2 },
  { id: 6, name: 'Node 6', parentId: null },
];
 
const tree = buildTree(list);
console.log(tree);

(3)使用reduce函数:

function buildTree(list) {
  const tree = list.reduce((acc, item) => {
    item.children = [];
    acc[item.id] = item;
    const parent = item.parentId ? acc[item.parentId] : null;    
    if (parent) {
      parent.children.push(item);
    } else {
      acc.push(item);
    }
    return acc;
  }, []);
  
  return tree;
}
 
const list = [
  { id: 1, name: 'Node 1', parentId: null },
  { id: 2, name: 'Node 2', parentId: 1 },
  { id: 3, name: 'Node 3', parentId: 1 },
  { id: 4, name: 'Node 4', parentId: 2 },
  { id: 5, name: 'Node 5', parentId: 2 },
  { id: 6, name: 'Node 6', parentId: null },
];
 
const tree = buildTree(list);
console.log(tree);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值