如何创建以下变量:
const city = 'Your city';
const state = 'your state';
const country = 'Country';
来自输入变量
const address = "Your city, your state, your country";
有没有在 JavaScript 中执行此操作的方法?
最佳答案
有很多方法可以解决这个问题。如果字符串始终采用 value1 <comma> value2 <comma> value3
的格式你可以很容易地使用 String.prototype.split()
从字符串中获取一个数组,然后将常量分配给数组索引:
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);
在 ES6 中,你可以使用解构赋值来缩短这段时间:
let address = "Your city, your state, your country";
address = address.split(", ");
const [city, state, country] = address;
console.log(city, state, country);
关于javascript - 使用 const 创建动态变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50464860/