gpt4 book ai didi

javascript - 如何在一行中console.log对象

转载 作者:行者123 更新时间:2023-12-02 20:53:06 24 4
gpt4 key购买 nike

我想修改这个对象

const myObject = { "first": ["x","y", "z"], "second": ["a", "b"], "third": ["c"] }
const string = "String!";
const count = () => {
const result = Object.entries(myObject ).forEach(([key, value]) =>
console.log(`${key} ${value.length > 1 ? ("x " + value.length) : ""} (${value})`)
);
return result;
};
count();

我来了

first x 3 (x, y, z)
second x 2 (a, b)
third (c)

我想获得此输出,如何将其放入一行和字符串中?或者我应该使用新功能?

String! first x 3 (x, y, z) – second x 2 (a, b) - third(c)

最佳答案

要获得您所说的想要的输出,您必须:

  1. 使用 map 构建条目数组,而不是输出这些字符串。

  2. 字符串添加到开头。

  3. 将数组转换为字符串,条目之间带有 "- ",可能通过 join("- ") 实现。

我还建议将 myObject 作为参数传递到 count 中,而不是直接使用它:

实例:

const myObject = { "first": ["x","y", "z"], "second": ["a", "b"], "third": ["c"] }
const string = "String!";
const count = (obj) => {
const result = Object.entries(obj).map(([key, value]) =>
`${key} ${value.length > 1 ? ("x " + value.length) : ""} (${value})`
);
return result;
};
console.log(string + " " + count(myObject).join(" - "));

或者,如果您想 count 内执行此操作,也可以传入字符串:

const myObject = { "first": ["x","y", "z"], "second": ["a", "b"], "third": ["c"] }
const string = "String!";
const count = (obj, str) => {
const result = Object.entries(obj).map(([key, value]) =>
`${key} ${value.length > 1 ? ("x " + value.length) : ""} (${value})`
);
return `${str} ${result.join(" - ")}`;
};
console.log(count(myObject, string));

关于javascript - 如何在一行中console.log对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61559654/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com