創建一個通用的查找功能,然後使用它:
function lookup(myArray, searchTerm, property, firstOnly) {
var found = [];
for (var i = 0; i < myArray.length; i++) {
if (myArray[i][property] === searchTerm) {
found.push(myArray[i]);
if (firstOnly) break; //if only the first
}
}
return found;
}
使用它:
var existUser = lookup(selectedUsers,"qid",$(this).val(),true);
if(existUser && existUser.length){// it returned a match if len > 0
push it here
}
這是一個有點冒險,如果有人已經查閱了,所以讓我們命名空間我噸,其他一些:)(更改myApp
到你)
使用:
var existUser = myApp.arrayObj.lookup(selectedUsers,"qid",$(this).val(),true);
或使用包含:
var hasUser = myApp.arrayObj.contains(selectedUsers,"qid",$(this).val());
功能:
var myApp = myApp || {};
myApp.arrayObj = {
indexOf: function(myArray, searchTerm, property) {
for (var i = 0; i < myArray.length; i++) {
if (myArray[i][property] === searchTerm) return i;
}
return -1;
},
indexAllOf: function(myArray, searchTerm, property) {
var ai = [];
for (var i = 0; i < myArray.length; i++) {
if (myArray[i][property] === searchTerm) ai.push(i);
}
return ai;
},
lookup: function(myArray, searchTerm, property, firstOnly) {
var found = [];
for (var i = 0; i < myArray.length; i++) {
if (myArray[i][property] === searchTerm) {
found.push(myArray[i]);
if (firstOnly) break; //if only the first
}
}
return found;
},
lookupAll: function(myArray, searchTerm, property) {
return this.lookup(myArray, searchTerm, property, false);
},
remove: function(myArray, searchTerm, property, firstOnly) {
for (var i = myArray.length - 1; i >= 0; i--) {
if (myArray[i][property] === searchTerm) {
myArray.splice(i, 1);
if (firstOnly) break; //if only the first term has to be removed
}
}
},
contains: function(myArray, searchTerm, property){
return this.indexOf(myArray, searchTerm, property) !== -1;
}
};
也許你不需要if條件 –
JS實際上並沒有關聯數組......如果你有字符串鍵,那麼你需要一個常規的對象,而不是一個數組。我建議爲選定的用戶創建一個對象而不是數組,然後你可以通過qid來索引它。 –
在我看來,這裏的對象陣列還是比較好的。畢竟,這是一個用戶列表。 – azium