【问题标题】:How do you call multiple keys from an object in one variable如何从一个变量中的对象调用多个键
【发布时间】:2021-03-16 13:29:19
【问题描述】:

这是代码

const restaurant = {
    name: 'Ichiran Ramen',
    address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
    city: 'Brooklyn',
    state: 'NY',
    zipcode: '11206',

我想创建一个变量“fullAddress”,它应该使用来自restaurant 的信息指向一个字符串 fullAdress 应该有地址城市州和邮政编码。

我的方法是

let fullAddress = restaurant.address;
fullAddress += restaurant.city;
fullAddress += restaurant.state;
fullAddress += restaurant.zipcode;

但这对我来说似乎很奇怪而且很冗长,而且中间没有空格。

任何帮助将不胜感激。

【问题讨论】:

标签: javascript variables


【解决方案1】:

你可以定义一个getter属性

const restaurant = {
    name: 'Ichiran Ramen',
    address: `${Math.floor(Math.random() * 100) + 1} Johnson Ave`,
    city: 'Brooklyn',
    state: 'NY',
    zipcode: '11206',
    get fullAddress() {
      const { address, city, state, zipcode } = this;
      return `${address} ${city} ${state} ${zipcode}`;
    }
}

console.log(restaurant.fullAddress);

【讨论】:

  • 请将您的答案添加到已识别的重复问题中,而不是回答这个问题。
  • 我认为这两个问题略有不同。您确定的答案是关于对象修改的,这是关于获取值的。
【解决方案2】:

您的方法并不过分冗长,而且阅读起来非常清晰,但是您没有在地址组件之间连接逗号和空格。要使用您的方法获得正确的结果:

let fullAddress = restaurant.address;
fullAddress += ', ';
fullAddress += restaurant.city;
fullAddress += ', ';
fullAddress += restaurant.state;
fullAddress += ', ';
fullAddress += restaurant.zipcode;

但是,如果您想要更简洁的方法,并且假设您在现代 (ES6) 环境中工作,您可以为此使用模板文字。

例如,如果您希望最终字符串为123 Johnson Ave, Brooklyn, NY, 11206

你可以这样写:

const fullAddress = `${restaurant.address}, ${restaurant.city}, ${restaurant.state}, ${restaurant.zipcode}`;

请注意,模板文字的语法使用反引号,而不是普通引号。

More information about template literals on MDN.

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多