Js中字符串,数组,对象之间相互转换

目录

一>字符串转数组

 <1>字符串转一维数组:

<2>字符串转二维数组: 

 <3>多个字符串转维数组: 

二>数组转字符串

三>数组转对象的方法

四>对象转数组的方法 

五>字符串转对象的方法  


一>字符串转数组

    <1>字符串转一维数组:

  1) 第一种方法: split( )

const n = 'abbdl'

const b = n.split('')

console.log('结果为:', b);//[ 'a', 'b', 'b', 'd', 'l' ]

 2) 第二种方法: Array.from( )

let str = 'hello'

let arr = Array.from(str)

console.log(arr);//[ 'h', 'e', 'l', 'l', 'o' ]

3) 第三种方法: 扩展运算符(...)

let str = 'Hello'

let arr = [...str]

console.log(arr);// [ 'H', 'e', 'l', 'l', 'o' ]

4) 第四种方法: 字符串的match( )

let str = 'hello world'

let arr = str.match(/\S+/g)

console.log(arr);// [ 'hello', 'world' ]

5) 第五种方法: Array.prototype.map.call()

//Array.prototype.map(): 将字符串中每个字符转换成数字,并将它们存储在一个数组中

let str = '122344'

let arr = Array.prototype.map.call(str,(x)=>{
    return parseInt(x)
})

console.log(arr);//[ 1, 2, 2, 3, 4, 4 ]

<2>字符串转二维数组: 

1)  第一种方法: 使用split()和map()

let str = '1,2,3;e,r,t;喀'

let arr = str.split(';').map(item=>item.split(','))

console.log(arr);//[ [ '1', '2', '3' ], [ 'e', 'r', 't' ], [ '喀' ] ]

 <3>多个字符串转维数组: 

const names = '张三'
const age = 23
const color = '橘黑色'
const infoArr = [names, age, color] //[ '张三', 23, '橘黑色' ]

二>数组转字符串

1) 第一种方法: 拼接字符串

const arr = ['one','two','three','four']

const str = arr + ''

console.log(str);//one,two,three,four

 2)第二种方法: 使用Array.prototype.toString()

const arr = ['one','two','three','four']

const str = arr.toString()

console.log(str);//one,two,three,four

 3)第三种方法:使用 Array.prototype.join方法

const arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']

const str = arr.join(", ");

console.log(str) // Sunday, Monday, Tuesday, Wednesday, Thursday

 4) 第四种方法: 使用Array.prototype.toLocaleString方法

const arr = ['one','two','three','four']

const str = arr.toLocaleString()

console.log(str);//one,two,three,four

5)第五种方法: 使用Array.prototype.join() 

const arr = ['one','two','three','four']

const str = arr.join(',')

console.log(str);// one,two,three,four

三>数组转对象的方法

1)  第一种方法: 使用ES6的扩展语法

const arr = ['one','two','three','four']

const obj = {...arr}

console.log(obj);//{ '0': 'one', '1': 'two', '2': 'three', '3': 'four' }

2)第二种方法: 使用for循环

const arr = ['one','two','three','four']

const obj = {}
for(let i=0;i<arr.length;i++){
    obj[i]= arr[i]
}
console.log(obj);// { '0': 'one', '1': 'two', '2': 'three', '3': 'four' }

3)  第三种方法: 使用object.assign()方法

const arr = ['one','two','three','four']

const obj = Object.assign({},arr)

console.log(obj);//{ '0': 'one', '1': 'two', '2': 'three', '3': 'four' }

4)第四种方法: 使用reduce()方法 

/* 
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
*prev:上次调用函数的返回值(必需)
*currentValue:当前的元素(必需)
*currentIndex:当前元素索引(可选)
*arr:当前元素所属的数组对象(可选)
*initialValue:传递给函数的初始值(可选)
*/

const arr = ['one', 'two', 'three', 'four']

const obj = arr.reduce((pre, cur, index) => {
    pre[index] = cur
    return pre
}, {})

console.log(obj);//{ '0': 'one', '1': 'two', '2': 'three', '3': 'four' }

四>对象转数组的方法 

1) 第一种方法:使用for...in

const obj = {
    a: 1,
    b: 2,
    c: 3
}

const arr = []

for (let key in obj) {
    arr.push(obj[key])
}
console.log(arr);// [ 1, 2, 3 ]

2)第二种方法:使用 Object.keys()

/* 
Object.keys():返回一个由对象的属性名组成的数组
*/
const obj = {
    a: 1,
    b: 2,
    c: 3
}

const arr = Object.keys(obj)
console.log(arr);//[ 'a', 'b', 'c' ]

3)  第三种方法:使用Object.values()

/* 
Object.values():返回一个由对象的属性值组成的数组
*/
const obj = {
    a: 1,
    b: 2,
    c: 3
}

const arr = Object.values(obj)

console.log(arr);//[ 1, 2, 3 ]

4) 第四种方法:使用Object.entries()

/* 
Object.entries():将对象的属性名和属性值转为二维数组。
*/
const obj = {
    a: 1,
    b: 2,
    c: 3
}

const arr = Object.entries(obj)

console.log(arr);//[ [ 'a', 1 ], [ 'b', 2 ], [ 'c', 3 ] ]

5) 第五种方法:使用Array.from(obj)

/* 
Array.from():将类数组对象或可迭代对象转为数组
*/
const obj1 = { 0: 'a', 1: 'b', 2: 'c', length: 3 };

const arr2 = Array.from(obj1);

console.log(arr2); // ['a', 'b', 'c']

五>字符串转对象的方法  

1)第一种方法:JSON.parse()

const str = '{"name":"小米","age":21}'

const obj = JSON.parse(str)

console.log(obj);//{ name: '小米', age: 21 }

2) 第二种方法:  字符串的eval()方法

onst str = '{"name":"小米","age":21}'

const obj = eval("("+str+")")

console.log(obj);//{ name: '小米', age: 21 }

3) 第三种方法:使用构造函数

const str = '{"name":"小米","age":21}'

const obj = (new Function("return" +str))()

console.log(obj);//{ name: '小米', age: 21 }

  • 6
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要将字符串数组转换对象数组,你需要先定义一个对象构造函数,该构造函数接受一个字符串参数并将其转换对象属性。然后,将字符串数组的每个字符串都传递给该构造函数,生成一个对象数组。 以下是一个示例代码,将一个包含字符串数组转换为一个包含对象数组: ```javascript // 定义对象构造函数 function Person(name, age) { this.name = name; this.age = age; } // 定义字符串数组 var peopleStr = ["{'name':'Alice', 'age':20}", "{'name':'Bob', 'age':30}", "{'name':'Charlie', 'age':40}"]; // 将字符串数组转换对象数组 var peopleObj = peopleStr.map(function(str) { return JSON.parse(str.replace(/'/g, "\"")); // 先将字符串的单引号替换为双引号,再解析为 JSON 对象 }).map(function(obj) { return new Person(obj.name, obj.age); // 使用对象构造函数生成对象 }); console.log(peopleObj); // 输出对象数组 ``` 在这个示例代码,我们首先定义了一个 `Person` 构造函数,用于将字符串转换对象。然后,我们定义了一个包含三个字符串数组 `peopleStr`,每个字符串都表示一个人的信息。接着,我们使用 `map` 方法遍历 `peopleStr` 数组,将其转换为包含三个 JSON 对象数组。由于 JSON 对象的属性名必须使用双引号而不是单引号,我们使用 `replace` 方法,包括添加课程和查看学生名单。 希望这个代码能够帮助到你,如果有什么问题欢迎再问!
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值