当前位置:网站首页>In JS, string and array are converted to each other (II) -- the method of converting array into string

In JS, string and array are converted to each other (II) -- the method of converting array into string

2022-07-06 21:10:00 viceen

js in , String and array conversion ( Two )—— The method of converting an array into a string

Method 1、toString() Method

1、 function : You can convert each element into a string , Then connect the output with commas and display it .

2、 Usage method :

var arr = [0,1,2,3];  // Define an array 
var str = arr.toString();  // hold arr Array utilization toString() Convert to string 
console.log(str);  // Input string '0,1,2,3'

When the array is in a string environment ,js Automatically called toString() Method to convert an array into a string .

var arr = [0,1,2,3];  //  Define an array 
var arr1 = [4,5,6,7];  //  Define an array 
var str = arr + arr1;  //  Array join operation 
console.log(str);  //  return '0,1,2,34,5,6,7'

var arr = [0,1,2,3];  //  Define an array 
var arr1 = [4,5,6,7];  //  Define an array 
var str = arr + ',' + arr1;  //  Array join operation 
console.log(str);  //  return '0,1,2,3,4,5,6,7'

toString() When converting an array to a string , First, convert each element of the array into a string . When each element is converted to a string , Use commas to separate , Output these strings as a list .

var arr = [[1,[2,3],[4,5]],[6,[7,[8,9],0]]];  //  Define multidimensional arrays 
var str = arr.toString();  //  Convert an array to a string 
console.log(str);  //  Return string '1,2,3,4,5,6,7,8,9,0'

Where array arr It's a multidimensional array ,JavaScript Will call... Iteratively toString() Method converts all arrays to strings .

Method 2、toLocalString() Method

1、 function : And toString() The method usage is basically the same , The difference lies in toLocalString() Method can concatenate the generated string with a user's locale specific delimiter , Form a string .

var array = [1,2,3,4,5];  //  Define an array 
var str = array.toLocaleString();  //  Convert an array to a local string 
console.log(str);  //  Return string '1,2,3,4,5'
  • According to Chinese usage habits , First convert the number to a floating-point number, and then perform the string conversion operation

Method 3、join() Method

1、 function : Convert an array to a string , However, it can specify the delimiter , If Omit parameters , By default comma As a separator

var arr = [1,2,3];  // Define an array 
var str = arr.join("-");  // Specify the separator -
console.log(str);  // Return string '1-2-3'

var arr = [1,2,3];  //  Define an array 
var str = arr.join(",");  //  Specify the separator 
console.log(str);  //  Return string '1,2,3'
原网站

版权声明
本文为[viceen]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207061250443914.html

随机推荐