前言:在项目过程中,我们会有很多情况会遇到我们拿到的的是一个数组的情况,但是后台可能需要的是一个以“,”分割的字符串,那我们有哪些方法进行转换呢?
1.我们首先for循环这个数组,将需要的值加”,”拼接起一个字符串,这个时候的字符串会以‘,’结尾,我们再用substring对这个字符串进行截取去掉最后的那个‘,’得到想要的值
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'); },
具体打印的信息如下图:

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/204566.html原文链接:https://javaforall.net
