[英]Javascript .find using one element to return another
I am a student.我是学生。 I'm trying to return one element based on one other.
我正在尝试基于另一个元素返回一个元素。 I need to use.find to search for the result "W" (the year a sports team won) and return the corresponding year.
我需要使用.find 搜索结果“W”(运动队获胜的年份)并返回相应的年份。 I'm expected to write
function (superbowlWin(record)
in order to satisfy this.为了满足这一点,我预计会写
function (superbowlWin(record)
。
const record = [
{ year: "1971", result: "N/A"},
{ year: "1970", result: "N/A"},
{ year: "1969", result: "W"},
{ year: "1968", result: "N/A"},
{ year: "1967", result: "N/A"},
{ year: "1966", result: "L"},
{ year: "1965", result: "N/A"},
{ year: "1964", result: "N/A"},
{ year: "1963", result: "N/A"},
{ year: "1962", result: "N/A"},
{ year: "1961", result: "N/A"},
{ year: "1960", result: "N/A"}
]
The array method filter and find make a good job for this task.数组方法 filter 和 find 可以很好地完成这项任务。 Both you will find below:
您将在下面找到两者:
const record = [ { year: "1971", result: "N/A"}, { year: "1970", result: "N/A"}, { year: "1969", result: "W"}, { year: "1968", result: "N/A"}, { year: "1967", result: "N/A"}, { year: "1966", result: "L"}, { year: "1965", result: "N/A"}, { year: "1964", result: "N/A"}, { year: "1963", result: "N/A"}, { year: "1962", result: "N/A"}, { year: "1961", result: "N/A"}, { year: "1960", result: "N/A"} ] let r = []; r1 = record.filter(x => x.result === 'W'); console.log('result filter: ',r1) r2 = record.find(x => x.result === 'W'); console.log('result find: ',r2)
Adding JSFiddle for ref https://jsfiddle.net/ug70xL4y/为参考https://jsfiddle.net/ug70xL4y/ 添加 JSFiddle
const record = [{ year: "1971", result: "N/A"},
{ year: "1970", result: "N/A"},
{ year: "1969", result: "W"},
{ year: "1968", result: "N/A"},
{ year: "1967", result: "N/A"},
{ year: "1966", result: "L"},
{ year: "1965", result: "N/A"},
{ year: "1964", result: "N/A"},
{ year: "1963", result: "N/A"},
{ year: "1962", result: "N/A"},
{ year: "1961", result: "N/A"},
{ year: "1960", result: "N/A"}];
function superbowlWin(records) {
let el = records.find(e=>e.result==='W');
if(el){
return el.year;
}else{
return undefined;
}
}
superbowlWin(record);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.