0

我们有大量的对象:

var englishStudents = [
    {StudentId: 1, Name: "John"},
    {StudentId: 2, Name: "Jack"},
    {StudentId: 3, Name: "Jane"}
];

需要检查另一个类似的对象是否包含在这个数组中,只需比较一个属性即可。

var randomStudent = {StudentId: 1337, Name: "Foo"};

这就是我所拥有的,似乎它会起作用,但我认为这不是最好的方法。

var studentIds = $.map(englishStudents, function (student, index) { return student.StudentId; });
var randomStudentLearnsEnglish = false;
for (var sId in studentIds) {
    if (randomStudent.StudentId == sId) {
        randomStudentLearnsEnglish = true;
        break;
    }
}

这样做的优化方法是什么?

4

4 回答 4

2

您应该将学生数据保存在像JHashtable这样的哈希表中,而不是数组中。对于更复杂的场景,你可以维护多个哈希表,比如studentsById,studentsByCountryCode等。

于 2013-01-31T22:31:22.587 回答
1

If all you want to know is if the ID exists can do this:

function checkIdExists( id){
    /* map array of matching ID, if none exists length of array is zero*/
    return  $.map(englishStudents, function (student, index) { 
               return student.StudentId==id; 
    }).get().length;
});

Use:

 if( checkIdExists( 1234)){
     /* run exists code*/
 }
于 2013-01-31T22:39:25.517 回答
1

只需做一个哈希而不是一个数组,所以:

var englishStudents = {
    1: {StudentId: 1, Name: "John"},
    2: {StudentId: 2, Name: "Jack"},
    3: {StudentId: 3, Name: "Jane"}
};

然后要检索,只需执行以下操作:

var student = englishStudents[id];
于 2013-01-31T22:30:37.563 回答
1

如果你真的想要,你可以创建一个进一步的索引方案:

var englishStudents = [
    {StudentId: 1, Name: "John"},
    {StudentId: 2, Name: "Jack"},
    {StudentId: 3, Name: "Jane"}
];
 //if doing this a lot of time, take the one time hit of construction and memory
var idToNameMap = createIdToNameMap(englishStudents); //returns {'1': 'John', '2': Jack' , '3': 'Jane'}

var randomStudent = getRandomStudent();
if( idToNameMap[ randomStudent.StudentId] != undefined){ ... }
于 2013-01-31T22:30:49.090 回答