使用const创建动态变量

时间:2018-05-22 10:00:09

标签: javascript string const

如何创建以下变量:

const city = 'Your city';
const state = 'your state';
const country = 'Country';

来自输入变量

const address = "Your city, your state, your country";

有没有方法可以在JavaScript中执行此操作?

3 个答案:

答案 0 :(得分:6)

有很多方法可以解决这个问题。如果字符串始终采用value1 <comma> value2 <comma> value3格式,您可以轻松地使用String.prototype.split()从String中获取数组,然后将常量分配给数组索引:

&#13;
&#13;
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);
&#13;
&#13;
&#13;

使用ES6,您可以使用解构分配使其更短:

&#13;
&#13;
let address = "Your city, your state, your country";

address = address.split(", ");

const [city, state, country] = address;

console.log(city, state, country);
&#13;
&#13;
&#13;

答案 1 :(得分:2)

试试这个。

    const address = "Your city, your state, your country";
    const splits = address.split(", ");

    const city = splits[0];
    const state = splits[1];
    const country = splits[2];

答案 2 :(得分:1)

您也可以这样做

const { 2: city, 3: state, 4: country } = address.split(', ');

console.log(city, state, country);