首页 > 解决方案 > 是否有 Javascript 函数将对象作为参数并返回字符串数组

问题描述

我希望有一个 javascript 函数,它可以将具有属性的对象作为参数,对其进行处理并将对象的属性作为字符串数组返回......到目前为止我正在尝试的代码在这里,但它打印出条目名称和属性名称

let Southampton={
    name:"Southampton",
    founded:1900,
    stadium:"St. Mary's Stadium",
    points:36
}
function printObj(arg) {
  for (let [key, value] of Object.entries(arg)) {
    console.log(`${key}: ${value}`);
  }
}
function printObj(Southampton)

上面的代码正在输出

name: Southampton
founded: 1900
stadium: St. Mary's Stadium
points: 36

是否可以对函数进行额外修改以使其返回 this

Southampton was founded in 1900

谢谢您的帮助

标签: javascriptarraysobject

解决方案


用于arg.map()通过对每个条目调用函数返回一个数组。

function obj_to_array(arg) {
    return Object.entries(arg).map(([key, value]) => `${key}: ${value}`);
}

要获取第二条消息,您不能使用这样的通用函数,因为它需要专门为founded属性格式化字符串。

function when_founded(arg) {
    return `${arg.name} was founded in ${arg.founded}`;
}

如果您真的希望它们都在一个函数中,您可以在返回数组之前打印消息。

let Southampton = {
  name: "Southampton",
  founded: 1900,
  stadium: "St. Mary's Stadium",
  points: 36
};

let Burnley = {
  name: "Burnley",
  founded: 1850,
  stadium: "Turf Moor",
  points: 33
};

let cities = [Southampton, Burnley];

function when_founded(arg) {
  return `${arg.name} was founded in ${arg.founded}`;
}

function obj_to_array(arg) {
  console.log(when_founded(arg))

  return Object.entries(arg).map(([key, value]) => `${key}: ${value}`);
}

console.log(obj_to_array(Southampton));

console.log(cities.map(when_founded))


推荐阅读