我有这个问题:
This function should take an argument as an object, and return a string with the user's details in the form:
'name: Mitch, age: 27, language: Javascript'
Note - this is a good use case of string template literals.
function createUserString(userObj) {
}
任何人都可以帮助解释如何将对象属性转换为完整字符串吗?
最佳答案
我想使用Object.entries()
和 Array.prototype.reduce()
一起可以解决您的问题。阅读他们的文档:
The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.
The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop.
看看可能的好解决方案:
const user = {
name: 'Mitch',
age: 27,
language: 'JavaScript',
nickName: 'Cool Mitch' // just added one more property for representation
};
const createUserString = user => {
const entries = Object.entries(user);
return entries.reduce((a, [k,v]) => a ? `${a}, ${k}: ${v}` : `${k}: ${v}`, '');
}
console.log(createUserString(user));
希望对您有所帮助!
关于javascript - 您可以使用字符串模板文字将整个对象作为字符串返回吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59922764/