admin 管理员组文章数量: 1086019
How to create the following variables:
const city = 'Your city';
const state = 'your state';
const country = 'Country';
From the input variable
const address = "Your city, your state, your country";
Are there any methods to do this in JavaScript?
How to create the following variables:
const city = 'Your city';
const state = 'your state';
const country = 'Country';
From the input variable
const address = "Your city, your state, your country";
Are there any methods to do this in JavaScript?
Share Improve this question edited May 22, 2018 at 15:03 Luca Kiebel 10.1k7 gold badges32 silver badges46 bronze badges asked May 22, 2018 at 10:00 Midhun JayanMidhun Jayan 2232 silver badges10 bronze badges 1-
.split
the string and then assign[0]
,[1]
and[2]
is the result to the appropriate constants…? – deceze ♦ Commented May 22, 2018 at 10:02
3 Answers
Reset to default 6There are a lot of ways to tackle this problem. If the string is always in the format of value1 <ma> value2 <ma> value3
you can easily use String.prototype.split()
to get an array from the String and then assign the constants to the array indexes:
let address = "Your city, your state, your country";
address = address.split(", ");
const city = address[0];
const state = address[1];
const country = address[2];
console.log(city, state, country);
With ES6 you can use destructuring assignments to make this even shorter:
let address = "Your city, your state, your country";
address = address.split(", ");
const [city, state, country] = address;
console.log(city, state, country);
Try this.
const address = "Your city, your state, your country";
const splits = address.split(", ");
const city = splits[0];
const state = splits[1];
const country = splits[2];
You can also do it like this
const { 2: city, 3: state, 4: country } = address.split(', ');
console.log(city, state, country);
本文标签: javascriptDynamic variable creation using constStack Overflow
版权声明:本文标题:javascript - Dynamic variable creation using const - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744099182a2533418.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论