通过删除逗号将数组转换为字符串javascript [英] Convert array to string javascript by removing commas

查看:42
本文介绍了通过删除逗号将数组转换为字符串javascript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数组 A 使得

I have an array A such that

A = [ '6', '6', '.', '5' ]

我想把它转换成一个字符串,这样当我console.log A时,它只返回66.5,即

I wish to convert it into a string, such that when I console.log A, it simply returns 66.5, ie

console.log(A) 
//expected Output
 66.5

目前,我得到的输出是

[ '6', '6', '.', '5' ]

当我做一个to字符串时,即 console.log(A.toString());,它给出输出 6,6,.,5,

When I do a to string, ie console.log(A.toString()); , it is giving the output 6,6,.,5,

当我尝试替换,"时使用",即 console.log(A = +A.toString().replace(,", ")) ,它给出了输出 A = 66,.,5

When I try to replace "," with "", ie console.log("A = "+A.toString().replace(",", "")) , it is giving the output A = 66,.,5

我如何制作它才能给出输出 A=66.5

How do I make it so that it gives the output A=66.5

推荐答案

你可以简单的使用Array.prototype.join函数

const A = [ '6', '6', '.', '5' ];

console.log(A.join(''));

文档页面上的解释Array.prototype.join

join() 方法通过连接数组(或类似数组的对象)中的所有元素,用逗号或指定的分隔符字符串分隔来创建并返回一个新字符串.如果数组只有一项,则该项将不使用分隔符返回.

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

它可以将分隔符作为参数,用于在连接时将元素与数组分开.

It can take as parameter the separator which will be use to separate element from the array when they are joined.

let list = ["a", "b", "c", "d"];

list.join("-"); // will return "a-b-c-d"
list.join("/"); // will return "a/b/c/d"
list.join(""); // will return "abcd"

默认分隔符是 ,.这意味着如果您不指定将使用哪个字符作为分隔符,它将使用 , 字符

By default the separator is ,. This means if you don't specify which character will be use as the separator it will use the , character

list.join(); // will return a,b,c,d

这篇关于通过删除逗号将数组转换为字符串javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆