文章目录
- 将数组转换为字符串
- join方法
- tostring方法
- toLocaleString
- 两个数组相加
- 将字符串转换为数组
- string.slice(start[, end])
- [...string]
- Array.from
- Object.values
在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"]