0

多数のオブジェクトがあります。

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

1つのプロパティだけを比較するだけで、この配列に別の同様のオブジェクトが含まれているかどうかを確認する必要があります。

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

配列の代わりにハッシュを実行するだけなので、次のようになります。

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 に答える
1

IDが存在するかどうかだけを知りたい場合は、次のように実行できます。

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;
});

使用する:

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