Conversion between strings and arrays

1. Four methods for converting strings to arrays

1. String.split(' ')

Insert image description here

 2. New methods of es6:Object.values(str);

Insert image description here

 3.Array.from(str)

Insert image description here

 4. The spread operator (...) in es6

Insert image description here

2. Convert array to string

Array methods illustrate
toString() Convert an array into a string
toLocaleString() Convert an array into a locally agreed string
join()

Concatenate array elements to build a string

1. tostring() method

The toString() method in the array can convert each element into a string, and then connect it with commas for output display.

var a = [1,2,3,4,5,6,7,8,9,0];  //定义数组
var s = a.toString();  //把数组转换为字符串
console.log(s);  //返回字符串“1,2,3,4,5,6,7,8,9,0”
console.log(typeof s);  //返回字符串string,说明是字符串类型

2. The toLocaleString() method reads the value of the array.

The toLocaleString() method is basically the same as the toString() method. The main difference is that the toLocalString() method can use the user's region-specific delimiter to concatenate the generated strings to form a string.

var a = [1,2,3,4,5];  //定义数组
var s = a.toLocaleString();  //把数组转换为本地字符串
console.log(s);  //返回字符串“1,2,3,4,5,6,7,8,9,0”
//在上面示例中,toLocaleString() 方法根据中国的使用习惯,
//先把数字转换为浮点数之后再执行字符串转换操作。

3. join() method

The join() method can be used below to convert the array into a string.

The join() method can convert an array into a string, but it can specify a delimiter. When calling the join() method, you can pass a parameter as a separator to join each element. If the parameter is omitted, comma is used as the delimiter by default, which has the same conversion effect as the toString() method.

var a = [1,2,3,4,5];  //定义数组
var s = a.join("==");  //指定分隔符
console.log(s);  //返回字符串“1==2==3==4==5”

3. Conversion between JSON objects/arrays and JSON strings

一、JSON.stringify()

 

JSON.stringify({});                        // '{}'
JSON.stringify(true);                      // 'true'
JSON.stringify("foo");                     // '"foo"'
JSON.stringify([1, "false", false]);       // '[1,"false",false]'
JSON.stringify({ x: 5 });                  // '{"x":5}'

JSON.stringify({x: 5, y: 6});
// "{"x":5,"y":6}"

2, JSON.parse()

 

JSON.parse('{}');              // {}
JSON.parse('true');            // true
JSON.parse('"foo"');           // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null');            // null

Guess you like

Origin blog.csdn.net/weixin_45441470/article/details/123755305