P粉3434089292023-08-19 09:40:13
The name of this function means you expect it to return a "title" (which I would interpret as a string value):
function findRecordTitle(records, id) { return records.find((record) => { return record.id === id; }) }
However, nowhere in this function does it have anything to do with "title". It returns a matching object (or null
) in the records
array. If you just want to return the title
property of the object, just return the property:
function findRecordTitle(records, id) { return records.find((record) => { return record.id === id; })?.title; // <--- 这里 }
EDIT: If your JavaScript environment is unable to use optional chaining, you can explicitly check for null
before trying to use the object:
function findRecordTitle(records, id) { const record = records.find((record) => { return record.id === id; }); return record ? record.title : null; }
Or it can default to an empty string instead of null
etc.