简体   繁体   English

接受对象并从该对象返回title属性值的javascript函数

[英]javascript function that accepts an object and returns the value of the title property from that object

I have a study item that states: Write a function bestShow that accepts an object and returns the value of the title property from that object. 我有一个研究项目,指出:编写一个功能bestShow,该函数接受一个对象并从该对象返回title属性的值。

Hint provided: console.log(bestShow({ genre: 'comedy', title: 'Seinfeld' })); 提供的提示:console.log(bestShow({genre:'comedy',title:'Seinfeld'}))); //Should print: Seinfeld //应该打印:Seinfeld

I've tried so many different things. 我尝试了很多不同的事情。 Here is one iteration, where I finally gave up. 这是一次迭代,我最终放弃了。

function bestShow(genre, title)
{
this.genre =  genre;
this.title = title;
}
var show = new bestShow(‘comedy’, ‘Seinfeld’);
console.log(show.bestShow.title);

This ES6 fat arrow function will do: 此ES6粗箭头功能将执行以下操作:

let title = (data) => data.title;

Pre ES6 version : ES6之前的版本

We will define a function, which accepts {genre: "comedy", title: "Sienfeld"} which is in-turn a valid JS object with properties genre and title . 我们将定义一个函数,该函数接受{genre: "comedy", title: "Sienfeld"} ,这又是一个具有genretitle属性的有效JS对象。 So all that is left there to do is to return the value of title property of our data parameter. 因此,剩下要做的就是返回data参数title属性的值。 Then we are just calling our function and using the result as an input for console.log . 然后,我们只是调用函数并将结果用作console.log的输入。

function title(data) {
 return data.title;
}
console.log(title({ genre: 'comedy', title: 'Seinfeld' }));

Why all this! 为什么所有这一切! Look it's so simple ! 看起来很简单!

function bestShow(obj) {
    return obj.title; 
}

Got it! 得到它了!

var bestShow = new Object();
    bestShow. genre = 'comedy';
    bestShow. title = 'Seinfeld';
console.log(bestShow.title);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JavaScript:创建一个接受数组和回调的函数groupBy,并返回一个对象 - JavaScript: Create a function groupBy that accepts an array and a callback, and returns an object Javascript,selectedIndex属性返回[object HTMLSelectElement] +值 - Javascript,selectedIndex property returns [object HTMLSelectElement] + the value javascript对象属性类型仅接受数字 - javascript object property type accepts only number 在 javascript 中编写一个接受任意数量的 object 的 function - write a function that accepts any number of object in javascript 异步函数,用于确定JavaScript对象中属性的值 - Async Function to determine the value of a property in a JavaScript object javascript函数搜索对象属性并返回值 - javascript function to search for object property and return value Javascript:属性的值为null或未定义,不是Function对象 - Javascript: The value of the property is null or undefined, not a Function object 在对象函数中访问Javascript属性的分配值 - Accessing the assigned value of a Javascript property in an object function Javascript:使用函数定义对象属性的值 - Javascript: Defining the value of object property using a function 自执行函数作为javascript中的对象属性值 - Self executing function as object property value in javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM