我有2个阵列
第一个数组有firstname
和lastname
第二个数组只有firstname
我将索引一个名字并检查数组
function whereIsAlice(persons) {
var index = 1;
for (var i = 0; i < friends1.length; i++) {
if (friends1[i].firstName === "Alice") {
index = i;
break;
}
if (friends2[i].firstName === "Alice") {
index = i;
}
}
return index
}
var friends1 = [{
firstName: 'John',
lastName: 'Gaudet'
},
{
firstName: 'Lisa',
lastName: 'Mcclanahan'
},
{
firstName: 'Alice',
lastName: 'Vore'
}, // Alice is here, at index 2
{
firstName: 'Marine',
lastName: 'Salsbury'
},
];
var friends2 = [{
firstName: 'Tim'
},
{
firstName: 'Arthur'
},
{
firstName: 'Juan'
},
];
console.log(whereIsAlice(friends1)); //Should be 2
console.log(whereIsAlice(friends2)); // Should be -1
两者的输出均为2。我该如何解决?
答案 0 :(得分:0)
如果你想编写自己的循环,你可以这样做。
var friends1 = [
{ firstName: 'John', lastName: 'Gaudet' },
{ firstName: 'Lisa', lastName: 'Mcclanahan' },
{ firstName: 'Alice', lastName: 'Vore' },
{ firstName: 'Marine', lastName: 'Salsbury' },
];
var friends2 = [
{ firstName: 'Tim' },
{ firstName: 'Arthur' },
{ firstName: 'Juan' },
];
const whereIsAlice = arr => {
for (let i = 0; i < arr.length; i++) {
if (arr[i].firstName === 'Alice') {
return i;
}
}
return -1;
}
console.log(whereIsAlice(friends1)); //Should be 2
console.log(whereIsAlice(friends2)); // Should be -1
答案 1 :(得分:0)
问题很容易。您正在比较whereIsAlice方法始终是第一个数组和第二个数组,然后该方法始终找到值并断开de for循环。
-Wno-deprecated-declarations
答案 2 :(得分:0)
为了简化您的功能,您可以使用下一个代码
function whereIsAlice(persons) {
return persons.map(function(e) { return e.firstName; }).indexOf('Alice');
}
var friends1 = [{
firstName: 'John',
lastName: 'Gaudet'
},
{
firstName: 'Lisa',
lastName: 'Mcclanahan'
},
{
firstName: 'Alice',
lastName: 'Vore'
}, // Alice is here, at index 2
{
firstName: 'Marine',
lastName: 'Salsbury'
},
];
var friends2 = [{
firstName: 'Tim'
},
{
firstName: 'Arthur'
},
{
firstName: 'Juan'
},
];
console.log(whereIsAlice(friends1)); //Should be 2
console.log(whereIsAlice(friends2)); // Should be -1
答案 3 :(得分:0)
重写您的功能如下所示,这将适用于您的情况:
function whereIsAlice(persons) {
var index= -1;
for(var i=0;i<persons.length;i++)
if(persons[i].firstName==="Alice"){index=i;break;}
return index;
}
答案 4 :(得分:0)
你们有些人从初始数组变异新数组(array.map
)并执行indexOf
。
其他人正在使用for
循环,然后检查变量index
。
那么为什么JS社区正在努力扩展语言结构,方法等?
我建议您更好地深入了解MDN并阅读findIndex?
function whereIsAlice(persons) {
return persons.findIndex(function(person) {
return person.firstName === 'Alice';
});
}
var friends1 = [
{
firstName: 'John',
lastName: 'Gaudet'
},
{
firstName: 'Lisa',
lastName: 'Mcclanahan'
},
{
firstName: 'Alice',
lastName: 'Vore'
}, // Alice is here, at index 2
{
firstName: 'Marine',
lastName: 'Salsbury'
},
];
var friends2 = [
{
firstName: 'Tim'
},
{
firstName: 'Arthur'
},
{
firstName: 'Juan'
},
];
console.log(whereIsAlice(friends1));
console.log(whereIsAlice(friends2));
&#13;
使用ES6,它太短了,我没有看到创建方法的理由:
console.log(friends1.findIndex(friend => friend.firstName === 'Alice'));
console.log(friends2.findIndex(friend => friend.firstName === 'Alice'));