JS 数组转字符串,字符串转数组方法汇总


在JavaScript中,我们经常需要将数组和字符串进行相互转换。幸运的是,JavaScript提供了一些方法来轻松地完成这些转换。

将数组转换为字符串

join方法

join方法可以将一个数组转换为一个字符串,并且返回该字符串。默认情况下,它会用逗号分隔每个元素,但是您也可以指定其他字符串作为分隔符。

语法:

array.join(separator)

其中:

  • separator:可选。指定用于分隔数组元素的字符串。

使用示例:

const fruits = ['apple', 'banana', 'orange'];
const fruitString = fruits.join(',');
console.log(fruitString); // 输出 "apple,banana,orange"

tostring方法

toString方法可以将一个数组转换为一个字符串。

使用示例:

const fruits = ['apple', 'banana', 'orange'];
const fruitString = fruits.toString();
console.log(fruitString); // 输出 "apple,banana,orange"

toLocaleString

toLocaleString方法与toString方法类似,但是它会使用本地化格式。

使用示例:

const prices = [1000, 2000, 3000];
const priceString = prices.toLocaleString('en-US', {style: 'currency', currency: 'USD'});
console.log(priceString); // 输出 "$1,000.00,$2,000.00,$3,000.00"

两个数组相加

直接使用两个数组相加操作也可以将数组转换成字符串

使用示例:

const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const newstring = array1 + array2
console.log(newstring); // '1,2,34,5,6'
将两个数组用 "+" 连接起来会将它们转换为字符串,并在它们之间添加逗号

将字符串转换为数组

string.slice(start[, end])

slice方法可以从一个字符串中提取指定的部分,并返回一个新的字符串。如果省略第二个参数,slice将返回从起始索引到字符串末尾的所有字符。

语法:

string.slice(start[, end])

其中:

  • start:必需。要提取的起始索引。
  • end:可选。要提取的结束索引。

使用示例:

const fruitString = 'apple,banana,orange';
const fruits = fruitString.slice(0, -1).split(',');
console.log(fruits); // 输出 ["apple", "banana", "orange"]

[…string]

使用展开运算符可以很容易地将一个字符串转换为一个字符数组。

使用示例:

const fruitString = 'apple,banana,orange';
const fruitArray = [...fruitString];
console.log(fruitArray); // 输出 ["a", "p", "p", "l", "e", ",", "b", "a", "n", "a", "n", "a", ",", "o", "r", "a", "n", "g", "e"]

Array.from

Array.from方法可以从一个可迭代对象(例如字符串、数组或类似数组的对象)创建一个新的数组。

语法:

Array.from(arrayLike[, mapFn[, thisArg]])

其中:

  • arrayLike:必需。要转换为数组的可迭代对象。
  • mapFn:可选。用来对每个元素进行操作的函数。
  • thisArg:可选。在mapFn函数中使用的this值。

使用示例:

const fruitString = 'apple,banana,orange';
const fruits = Array.from(fruitString.split(','));
console.log(fruits); // 输出 ["apple", "banana", "orange"]

Object.values

Object.values方法可以返回一个对象中所有属性的值组成的数组。

语法:

Object.values(obj)

其中:

  • obj:必需。要获取属性值的对象。

使用示例:

const fruitObj = 'applebananaorange';
const fruits = Object.values(fruitObj);
console.log(fruits); // // 输出 ["a", "p", "p", "l", "e", ",", "b", "a", "n", "a", "n", "a", ",", "o", "r", "a", "n", "g", "e"]
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

有趣的小良

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值