求解-javascript数组字符串分割赋值给对象
javascript吧
全部回复
仅看楼主
level 1
有一个字符串数组必要把需的字符串进行分割后赋值给对象的值,有没有什么更高效的方法?
const strs=['1 张三 广州','2 李四 四川'] //需要分割的字符串数组
const userArr=[] //存储对象数组
function UserInfo(id,name,address){
this.id=id,
this.name=name,
this,address=address
} //构造函数
for(let i=0;i<strs.length;i++){
const userInfo = new UserInfo()
const user= strs[i].split(' ') //对数字里的字符串进行分割
userInfo.id= user[0]
userInfo.name = user[1]
userInfo.address = user[2]
userArr.push(userInfo)
}
有没有更好的方法,最好是不要用userInfo.id = user[0]这样指定下标赋值的。。求大神解答
2023年07月01日 00点07分 1
level 13
2023年07月01日 06点07分 2
茅塞顿开,谢谢大神[真棒]
2023年07月01日 09点07分
level 12
const strs = ['1 张三 广州', '2 李四 四川'];
const userArr = strs.map(item => {
const [id, name, address] = item.split(' ');
return { id, name, address };
});
console.log(userArr);
2023年07月01日 08点07分 3
谢谢,还是得有你们来指点[真棒]
2023年07月01日 09点07分
level 12
或者像2楼大佬那样
2023年07月01日 08点07分 5
level 12
如果能普通对象代替实例的话 可以用我的3楼写法 [乖]
2023年07月01日 08点07分 7
level 12
class UserInfo {
constructor(id, name, address) {
this.id = id;
this.name = name;
this.address = address;
}
}
const strs = ['1 张三 广州', '2 李四 四川'];
// 参考2楼大佬的 [吐舌]
const userArr = strs.map(str => new UserInfo(...str.split(' ')));
console.log(userArr);
2023年07月01日 08点07分 8
1