【问题标题】:JavaScript: How do I concatenate two values from a single Object? [closed]JavaScript:如何连接来自单个对象的两个值? [关闭]
【发布时间】:2019-10-31 17:41:32
【问题描述】:

我知道这很简单,但无论出于何种原因,我现在完全被难住了。

我有一个对象数组,它们都有自己的monthyear 属性,我试图将每个对象的两者连接起来,然后将它们一起显示。我的数据如下:

"caloriesBurned": [
        {
            "month": "Nov",
            "year": "2018",
            "calories": 64.15
        },
        {
            "month": "Dec",
            "year": "2018",
            "calories": 75.07
        }
]

【问题讨论】:

  • 以什么方式连接它们?显示您期望的结果。
  • StackOverflow 不是免费的编码服务。你应该try to solve the problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并拨打tour :)
  • obj.caloriesBurned[i].month + obj.caloriesBurned[i].year
  • 你可以试试console.log(caloriesBurned.map(item => item.month + " " + item.year));

标签: javascript concatenation


【解决方案1】:

你可以这样做

let arrayResult = []
for(let i=0; i< caloriesBurned.length; i++){debugger
    test = i+ ":->" + caloriesBurned[i].month + " " + caloriesBurned[i].year;
    arrayResult.push(test)
}

或者如果需要使用 ES6 则只使用 map 函数,那么不需要使用 for 循环而不是使用 map 作为高阶函数,然后可以更简单的方式实现,如果不方便,那么可以也可以使用上面的代码。

【讨论】:

    猜你喜欢
    • 2020-05-11
    • 2011-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-18
    • 2018-09-20
    • 1970-01-01
    相关资源
    最近更新 更多