개체 배열이 있습니다. 각 개체에는 ID 특성이 있습니다. 나는 특정 ID를 가진 객체의 배열에서 색인을 찾고 싶다. jQuery에서 우아하고 간단한 방법이 있습니까?jQuery : 배열의 요소 색인 어디에서 술어
답변
이 경우에는 for
루프를 jQuery 대신 javascript에 사용해야합니다. 방법 3을 참조하십시오 http://net.tutsplus.com/tutorials/javascript-ajax/10-ways-to-instantly-increase-your-jquery-performance/
업데이트 : jQuery는 자바 스크립트로 작성되었으며 자바 스크립트로 작성된 다른 코드보다 빠를 수 없습니다. DOM을 사용하여 작업하는 경우 jQuery는 매우 유용하지만 단순한 자바 스크립트 배열이나 객체로 작업하는 경우에는 도움이되지 않습니다.
for (var i=0, l = ar.length; i<l; i++) {
if (ar[i].ID === specificID) {
// i is the index. You can use it here directly or make a break
// and use i after the loop (variables in javascript declared
// in a block can be used anywhere in the same function)
break;
}
}
if (i<l) {
// i is the index
}
중요 몇 가지 간단한 자바 스크립트 규칙을 유지해야 : 항상 지역 변수 (변수 선언하기 전에 var
을 잊지 마세요) 및 캐시를 선언
당신이 찾고있는 코드는 다음과 같은 수 있습니다 위의 ar.length
과 같은 로컬 변수에서 두 번 이상 사용하는 속성이나 인덱스 당신이 백필 수
체크 아웃 findIndex
findIndex
이후
items.findIndex(function(item) { item.property == valueToSearch; });
ECMAScript를 6에서 아직 대부분의 브라우저에서 사용할 수 없습니다 :
정말 우아한 아니지만, 귀여운 트릭 :
var index = parseInt(
$.map(array, function(i, o) { return o.id === target ? i : ''; }).join('')
);
jQuery를 그런 기능적인 구조의 여지가없는; 도서관의 철학은 실제로 DOM 논쟁의 일에 집중되어 있습니다. 아무도 핵심 기능에 유용 할 이유를 생각할 수 없기 때문에 그들은 .reduce()
기능을 추가하지 않습니다.
Underscore.js 라이브러리에는 이러한 기능이 많이 있으며 jQuery로 "훌륭하게"재생됩니다.
See [`Array.filter`][1] to filter an array with a callback function. Each object in the array will be passed to the callback function one by one. The callback function must return `true` if the value is to be included, or false if not. var matchingIDs = objects.filter(function(o) { return o.ID == searchTerm; }); All objects having the ID as searchTerm will be returned as an array to matchingIDs. Get the matching element from the first index (assuming ID is unique and there's only gonna be one) matchingIDs[0]; [1]: https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Objects/Array/filter
업데이트 (http://wiki.forum.nokia.com/index.php/JavaScript_Performance_Best_Practices 예를 들어, 참조) 그것을 사용하는이 implementation :
if (!Array.prototype.findIndex) {
Array.prototype.findIndex = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.findIndex called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return i;
}
}
return -1;
};
}
jOrder를 사용하십시오. http://github.com/danstocker/jorder
배열을 jOrder 테이블에 넣고 'ID'필드에 색인을 추가하십시오. 당신은 전체 행을 원한다면,
var arrayidx = table.index('id').lookup([{ ID: MyID }]);
:
var table = jOrder(data)
.index('id', ['ID']);
그런 다음에 의해 요소의 배열 인덱스를 얻을 수
var filtered = table.where([{ ID: MyID }]);
짜잔합니다.
기본 제공되는 방법이 없습니다. [].indexOf()
방법은 조건을 고려하지 않습니다, 그래서 당신은 뭔가 정의해야합니다
function indexOf(array, predicate)
{
for (var i = 0, n = array.length; i != n; ++i) {
if (predicate(array[i])) {
return i;
}
}
return -1;
}
var index = indexOf(arr, function(item) {
return item.ID == 'foo';
});
함수는 -1을 반환 술어가 결코 truthy 값을 얻을 수없는 경우입니다.
- 1. jQuery 요소 색인
- 2. jquery 와일드 카드 선택기 - 양식 요소 배열의 색인
- 3. 요소, jQuery 또는 Javascript 색인
- 4. 배열의 색인 순서를 변경하십시오.
- 5. 요소 배열의 각 요소에 값 배열의 각 elem을 할당합니다. jQuery
- 6. 배열의 특정 항목 색인 얻기
- 7. IndexOf 술어?
- 8. 해시 배열의 요소 찾기
- 9. 배열의 요소 이동 C++
- 10. 배열의 마지막 요소
- 11. 배열의 요소 개수가?
- 12. Java에서 배열의 요소 찾기
- 13. 배열의 해당 요소 교환
- 14. Mootools 배열의 액세스 요소
- 15. Prolog 정렬을위한 술어
- 16. MongoDB C# 배열의 배열 색인 또는 색인 내부 항목
- 17. PHP foreach 루프 요소 색인
- 18. jQuery .each() 함수. 색인 재설정?
- 19. 술어 Common Lisp
- 20. 2D 배열의 요소 교체 C#
- 21. 배열의 요소 순위를 효율적으로 찾습니까?
- 22. 개체 배열의 요소 개수 (크기)
- 23. PHP에서 배열의 요소/JSON 에코
- 24. Java에서 문자열 배열의 요소 비교
- 25. 배열의 첫 번째 요소 $$ foo
- 26. jQuery 색인 문제()
- 27. 배열의 Jquery 함수
- 28. 술어 캐시
- 29. LINQ의 술어
- 30. 술어 사용
정확히 내가 무엇을 찾고 있는지. 참으로 나쁜 해결책이 없다 ... – epeleg