【问题标题】:How to make a variable using keys from literal object, javascript如何使用文字对象中的键创建变量,javascript
【发布时间】:2021-03-18 19:14:36
【问题描述】:

在练习中,我必须创建一个名为“fullAddress”的变量,它包含给定文字对象中除第一个键之外的所有内容。

我找到了一种可行的解决方案,但我觉得有更好的方法来做到这一点。另外,我不知道如何有效地在变量中的值之间放置空间。

练习表明最终结果应如下所示:

39 Johnson Ave, 布鲁克林, NY, 11206

但我的看起来像这样:

39 Johnson AveBrooklynNY11206


练习中提供的文字对象:

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

我的解决方案:

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

【问题讨论】:

标签: javascript key


【解决方案1】:

给定一个字符串数组,您可以使用values.join(', ') 在值之间干净地放置逗号。然后你可以做例如[restaurant.address, restaurant.city, restaurant.state, restaurant.zipcode].join(', ').

如果您想对任何对象更通用地执行此操作,您可以使用Object.values(restaurant).slice(1).join(', ') 动态获取第一个值之后的所有值并用逗号分隔它们。

不过,在这种情况下,我认为显式附加逗号是最有意义的,因为它是一种地址格式(例如,您可能不希望在邮政编码后有空格),所以像 restaurant.address + ', ' + restaurant.city + ...

【讨论】:

  • 谢谢!这一切都很有意义。
【解决方案2】:

关于空格(和逗号),您可以像 restaurant.address 一样使用模板字符串。

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

let fullAddress = `${restaurant.address}, ${restaurant.city}, ${restaurant.state}, ${restaurant.zipcode}`;
console.log(fullAddress); // 39 Johnson Ave, Brooklyn, NY, 11206

接下来,请注意我们实际上使用相同的分隔符连接所有地址部分:', '。这意味着我们可以改用[].join()

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

let addressParts = [restaurant.address, restaurant.city, restaurant.state, restaurant.zipcode];
let fullAddress = addressParts.join(', ');
console.log(fullAddress); // 39 Johnson Ave, Brooklyn, NY, 11206

最后,(如果你想花哨的话),请注意restaurant. 是重复的。使用[].map() 可以避免这种情况。

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

let fullAddress = ['address', 'city', 'state', 'zipcode']
    .map(key => restaurant[key])
    .join(', ');
console.log(fullAddress); // 39 Johnson Ave, Brooklyn, NY, 11206

【讨论】:

  • 感谢您提供所有信息!我忘记了模板文字。我还没有学过地图——我得研究一下。
【解决方案3】:

你可以从餐厅对象中取出所有的值,去掉第一个元素,然后使用join得到想要的字符串

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

const fullAddress = Object.values(restaurant).slice(1).join(', ');
console.log(fullAddress);

【讨论】:

    猜你喜欢
    • 2018-01-30
    相关资源
    最近更新 更多