【问题标题】:Dynamic variable creation using const使用 const 创建动态变量
【发布时间】:2018-05-22 10:00:09
【问题描述】:

如何创建以下变量:

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

从输入变量

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

在 JavaScript 中有什么方法可以做到这一点吗?

【问题讨论】:

  • .split 字符串然后赋值[0][1][2] 是结果到适当的常量...?

标签: javascript string constants


【解决方案1】:

有很多方法可以解决这个问题。如果字符串始终采用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);

【讨论】:

    【解决方案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];
    

    【讨论】:

      【解决方案3】:

      你也可以这样做

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

      【讨论】:

        猜你喜欢
        • 2013-06-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-19
        • 2011-02-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多