假设有一个对象数组,每个对象包含两个属性:id和name。现在我们需要遍历这个数组并比较每个对象的属性值,以找到符合条件的对象。
代码示例:
const data = [ { id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }, { id: 3, name: 'Charlie' }, { id: 4, name: 'David' }, ];
function findObjectById(idToFind) { for (let i = 0; i < data.length; i++) { const currentObject = data[i]; if (currentObject.id === idToFind) { return currentObject; } } return null; }
function findObjectByName(nameToFind) { const matchingObjects = []; for (let i = 0; i < data.length; i++) { const currentObject = data[i]; if (currentObject.name === nameToFind) { matchingObjects.push(currentObject); } } return matchingObjects; }
// 查找 id 为 3 的对象 const foundObjectById = findObjectById(3); console.log(foundObjectById); // { id: 3, name: 'Charlie' }
// 查找名字为 'Bob' 的所有对象 const foundObjectsByName = findObjectByName('Bob'); console.log(foundObjectsByName); // [ { id: 2, name: 'Bob' } ]