05. How to convert the data of a two-dimensional array (an array inside an array) into a string

1. Data situation:

First, the data obtained from the backend is:let arr = [1,[10,20],[20,30],40]

Second, the target data is:'1,10-20,20-30,40'

2. Operation process:

First, convert the data into:[1, '10-20', '20-30', 40]

A. Code display:


let arr = [1,[10,20],[20,30],40]
let first_res =  arr.map(item => {
    
    
  if(Array.isArray(item)) {
    
      // 此时是为了区分 item 是二维的数组还是非数组的值;
    let res = item.join("-") // 此时是将二维数组中的 ',' 换成 '-' 的操作;
    return res   // 将操作后的二维数组返回;
  } else {
    
    
    return item // 将非数组的值返回;
  }
})
console.log(first_res,565656);   // 此时的输出结果为:[1, '10-20', '20-30', 40]

B. Result display:

Insert image description here

Second, convert the data into target data:'1,10-20,20-30,40'

A. Code display:


let first_res = [1, '10-20', '20-30', 40]
let second_res = first_res.map(it => {
    
    
        if(typeof it === "string") {
    
     // 此时是区分:it 是字符串类型和非字符串类型;
          return it   // 字符串类型就直接返回;
        } else {
    
    
          let res = it.toString()  // 非字符串类型就转化成字符串类型再返回;
          return res
        }
      })
      console.log(second_res, 787878787); // 此时的输出结果为:['1', '10-20', '20-30', '40'] (即:字符串类型的数组)
      console.log(second_res.toString(),78978999999); // 此时的输出结果就是目标值:'1,10-20,20-30,40'
      

B. Result display:

Insert image description here

3. Summary:

First, if there is anything wrong or inappropriate, please give me some pointers and exchanges!
Second, if you forward or quote the content of this article, please indicate the address of this blog ( 直接点击下面 url 跳转) https://blog.csdn.net/weixin_43405300 . Creation is not easy, but it must be done and cherished!
Third, if you are interested, you can pay more attention to this column (Vue (Vue2+Vue3) essential column for interviews) ( 直接点击下面 url 跳转): https://blog.csdn.net/weixin_43405300/category_11525646.html?spm=1001.2014.3001.5482

Guess you like

Origin blog.csdn.net/weixin_43405300/article/details/132722677