const array = [
{id: 'bbb'},
{id: 'aaa'},
{id: 'ccc'}
];
let targetIndex = -1;
for(let i = 0; i < array.length; i++) {
if(array[i].id === 'aaa') {
targetIndex = i;
break;
}
}
if(targetIndex !== -1) {
console.log('ID为aaa的对象下标是:' + targetIndex);
} else {
console.log('数组中没有ID为aaa的对象');
}
ES6 写法:
const array = [
{id: 'bbb'},
{id: 'aaa'},
{id: 'ccc'}
];
const targetObj = array.find(obj => obj.id === 'aaa');
if(targetObj) {
const targetIndex = array.findIndex(obj => obj.id === 'aaa');
console.log('ID为aaa的对象下标是:' + targetIndex);
} else {
console.log('数组中没有ID为aaa的对象');
}