编写一个名为stringFromObject的函数,该函数从对象的键/值对生成一个字符串

问题描述 投票:0回答:1

我正在尝试编写一个名为stringFromObject的函数,该函数从一个对象的键/值对生成一个字符串。

格式应为“键=值,键=值”。

每个键/值对应以逗号和空格分隔,最后一对除外。

到目前为止,我的代码:

    //write function that accepts an obj.
function stringFromObject(obj) {
  let result = "";
  //loop over the object's properties and create a new string
  //return format should be "key = value, key = value"
  for (let i in obj) {
    result += i + ' =' + obj[i];
  }
  result += '';
  //return a string 
  return result;
}

stringFromObject({ a: 1, b: '2' }); 
// "a = 1, b = 2"

输出应为// "a = 1, b = 2",但是我返回=> 'a =1b =2'。我对如何返回带有值的两个键感到困惑,但省略了逗号?有什么建议可以纠正吗?

javascript arrays javascript-objects helper javahelp
1个回答
2
投票

要在每个条目之间添加逗号,最好具有可以.join的条目数组。您可以使用Object.entries获取条目数组,它为您提供键及其关联的值-只需将它们与=连接在一起即可:

function stringFromObject(obj) {
  return Object.entries(obj)
    .map(([key, val]) => `${key} = ${val}`)
    .join(', ');
}

console.log(stringFromObject({ a: 1, b: '2' }));

要调整您现有的代码,请在,之后连接一个obj[i],然后在循环之后,切掉最后两个字符-但这仍然是不太优雅的IMO:

//write function that accepts an obj.
function stringFromObject(obj) {
  let result = "";
  //loop over the object's properties and create a new string
  //return format should be "key = value, key = value"
  for (let i in obj) {
    result += i + ' = ' + obj[i] + ', ';
  }
  // remove last comma and space
  result = result.slice(0, result.length - 2);
  return result;
}

console.log(stringFromObject({ a: 1, b: '2' }));
© www.soinside.com 2019 - 2024. All rights reserved.