javascript - 使用 const 创建动态变量

标签 javascript string constants

如何创建以下变量:

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/

相关文章:

javascript - 无法调用未定义的方法 "getValues"

ACE 编辑器中的 Javascript 智能感知

c++ - 如何在 C++ 中使用常量数组的成员函数?

c++ - 从文本文件中读取行数并将它们存储为数组大小的常量 int c++

javascript - 以一定 Angular 绘制到 y 值的线

javascript - 调试ajax,重新发送请求

javascript - 如何将数字转换为字符串并将其用作 JavaScript 中的数组键?

python - 通过python计算文本文件中的单词

php - 如何从 24 个字符的字符串中获取唯一的 8 个字符的字符串?

c - 为什么 char *s = "string"在不是 const 时不显示错误或警告