簡體   English   中英

如何在javascript中返回帶有對象的字符串?

[英]How do I return a string with an object in javascript?

我正在努力完成這個家庭作業。 我被困在第二個,我必須返回一個帶有對象鍵值的字符串。 當我將這種語法用於 name 鍵時,我認為我是對的。 但是,即使 console.log 顯示了名稱,結果顯示我做錯了。 所以我用傳統的方式嘗試了它,但又犯了另一個錯誤。 我不知道他們希望我如何做到這一點。 只要能產生相同的結果,我怎么做並不重要,但我想學校不會教這個。

/**
 * ### Challenge `getName`
 * 
 * @instructions
 * This function takes as its only argument
 * an object containing a `name` property,
 * and return a string that reads `Hello, my name is {name}`,
 * where `{name}` is the name stored in the object.
 * 
 * For example, if we invoke `getName`
 * passing { id: 1, name: 'Leia', email: 'leia@leia.com` } as the argument,
 * the returned value should look like `Hello, my name is Leia`.
*/


function getName(name) {

  var hallo = {

    name: name

  };

 return 'Hello, my name is' + ' ' + hallo.name;
}

正如@Amadan 所說,您正在接收一個對象作為參數。 參數不應是name ,而是諸如person東西。 然后您將返回一個字符串並使用person.name

您可以在將對象傳遞到您的函數時對其進行解構,只訪問分配所需的屬性:


let passing = { id: 1, name: 'Leia', email: 'leia@leia.com` }

傳入您需要使用的所需屬性。 必須有相同的名字

function getName( { name /*, email, id*/} ) {

 return `Hello my name is ${name}`; //You can also return a console log

} 

let instance1 = getName( passing);
console.log(instance1);

如果它幫助任何人。 這對我有用。

function getName(person) { return Hello, my name is ${person.name} ; }

按照評論中的文檔,您希望您的函數如下所示:

 /** * ### Challenge `getName` * * @instructions * This function takes as its only argument * an object containing a `name` property, * and return a string that reads `Hello, my name is {name}`, * where `{name}` is the name stored in the object. * * For example, if we invoke `getName` * passing { id: 1, name: 'Leia', email: 'leia@leia.com` } as the argument, * the returned value should look like `Hello, my name is Leia`. */ function getName(person) { return 'Hello, my name is ' + person.name; } const person = { id: 1, name: 'Leia', email: 'leia@leia.com' }; console.log(getName(person));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM