JS 数组转字符串的4种方法

前言:在项目过程中,我们会有很多情况会遇到我们拿到的的是一个数组的情况,但是后台可能需要的是一个以“,”分割的字符串,那我们有哪些方法进行转换呢? 

1.我们首先for循环这个数组,将需要的值加”,”拼接起一个字符串,这个时候的字符串会以‘,’结尾,我们再用substring对这个字符串进行截取去掉最后的那个‘,’得到想要的值

2.toString() 方法能够把每个元素转换为字符串,然后以逗号连接输出显示JavaScript 会以迭代的方式调用 toString() 方法把所有数组都转换为字符串。

3.toLocalString() 方法与 toString() 方法用法基本相同,主要区别在于 toLocalString() 方法能够使用用户所在地区特定的分隔符把生成的字符串连接起来,形成一个字符串

4.join() 方法可以把数组转换为字符串,不过它可以指定分隔符。在调用 join() 方法时,可以传递一个参数作为分隔符来连接每个元素。如果省略参数,默认使用逗号作为分隔符,这时与 toString() 方法转换操作效果相同。 

 

具体的代码实现如下

data() {
    return {
      formArr: ["科比", "麦迪", "卡特", "艾弗森"],
      note1: "",
      note2: "",
      note3: "",
      note4: "",
    };
  },
  created() {
    console.log(this.formArr);
    // 方法一

    let str = "";
    for (let i = 0; i < this.formArr.length; i++) {
      str += this.formArr[i] + ",";
    }
    this.note1 = str.substring(0, str.length - 1);
    console.log(this.note1,'note1');
    // 方法二
    this.note2 = this.formArr.toString();
    console.log(this.note2,'note2');
    // 方法三
    this.note3 = this.formArr.toLocaleString();
    console.log(this.note3,'note3');
     // 方法四
    this.note2 = this.formArr.join('&');
    console.log(this.note2,'note4');
  },

具体打印的信息如下图:

《JS 数组转字符串的4种方法》

 

    原文作者:心之所向_gp
    原文地址: https://blog.csdn.net/weixin_55182699/article/details/120425267
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞