javascript - 是否有 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
谢谢您的帮助
解决方案
用于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))
推荐阅读
- mips - 使用python模拟发送用户输入到spim
- python - 在分组条形图中显示负值的问题(matplotlib)
- sql - SQL 排除条件值
- spring-boot - Spring 如何知道在哪里搜索组件或 Bean?
- java - 在线程“main”java.lang.NoClassDefFoundError:scala/Function1$class 中获取 Akka 流代码时出错
- python - 创建一个可以创建多个类的python脚本
- python - 旋转的图片不显示在烧瓶中
- python - 当我打开 Jupyter 时,如何将 Anaconda 中的不同环境设置为默认使用不同版本的 Python?
- spring-boot - 记录 Web 依赖的条件评估报告
- java - JavaFx:如何拆分字符串并在 UI 上显示拆分字符(“:”)