"for (… in…)"루프의 요소 순서
Javascript의 "for… in"루프는 해시 테이블 / 요소를 선언 된 순서대로 반복합니까? 순서대로하지 않는 브라우저가 있습니까?
사용하려는 객체가 한 번 선언 되고 수정되지 않습니다.
내가 가지고 있다고 가정 해보십시오.
var myObject = { A: "Hello", B: "World" };
그리고 나는 그들을 더 사용합니다 :
for (var item in myObject) alert(item + " : " + myObject[item]);
가장 괜찮은 브라우저에서 'A : "Hello"가 항상'B : "World" '앞에 올 것으로 기대할 수 있습니까?
인용 존 레식 :
현재 모든 주요 브라우저는 객체의 속성을 정의 된 순서대로 반복합니다. Chrome은 몇 가지 경우를 제외하고이 작업도 수행합니다. [...]이 동작은 ECMAScript 사양에 의해 명시 적으로 정의되어 있지 않습니다. ECMA-262의 섹션 12.6.4 :
속성을 열거하는 메커니즘은 구현에 따라 다릅니다.
그러나 사양은 구현과는 다릅니다. ECMAScript의 모든 최신 구현은 정의 된 순서대로 객체 속성을 반복합니다. 이 때문에 Chrome 팀은이 버그로 간주하여 수정합니다.
모든 비 숫자 속성 이름에 대해 수행하는 Chrome 및 Opera를 제외한 모든 브라우저는 정의 순서 를 따릅니다. 이 두 브라우저에서 속성은 숫자가 아닌 첫 번째 속성보다 순서대로 가져옵니다 (배열을 구현하는 방법과 관련이 있음). 순서도 동일 Object.keys
합니다.
이 예제는 어떤 일이 발생하는지 명확히해야합니다.
var obj = {
"first":"first",
"2":"2",
"34":"34",
"1":"1",
"second":"second"
};
for (var i in obj) { console.log(i); };
// Order listed:
// "1"
// "2"
// "34"
// "first"
// "second"
이것의 기술은 이것이 언제라도 변할 수 있다는 사실보다 덜 중요합니다. 이런 식으로 머무는 것에 의존하지 마십시오.
간단히 말해 : 순서가 중요한 경우 배열을 사용하십시오.
1 년 후이 문제를 범핑하는 중 ...
그것은이다 2012 및 주요 브라우저는 여전히 차이 :
function lineate(obj){
var arr = [], i;
for (i in obj) arr.push([i,obj[i]].join(':'));
console.log(arr);
}
var obj = { a:1, b:2, c:3, "123":'xyz' };
/* log1 */ lineate(obj);
obj.a = 4;
/* log2 */ lineate(obj);
delete obj.a;
obj.a = 4;
/* log3 */ lineate(obj);
사파리 5, 파이어 폭스 14
["a:1", "b:2", "c:3", "123:xyz"]
["a:4", "b:2", "c:3", "123:xyz"]
["b:2", "c:3", "123:xyz", "a:4"]
Chrome 21, Opera 12, 노드 0.6, Firefox 27
["123:xyz", "a:1", "b:2", "c:3"]
["123:xyz", "a:4", "b:2", "c:3"]
["123:xyz", "b:2", "c:3", "a:4"]
IE9
[123:xyz,a:1,b:2,c:3]
[123:xyz,a:4,b:2,c:3]
[123:xyz,a:4,b:2,c:3]
로부터 인 ECMAScript 언어 사양 (온 섹션 12.6.4 for .. in
루프) :
속성을 열거하는 메커니즘은 구현에 따라 다릅니다. 열거 순서는 개체에 의해 정의됩니다.
4.3.3 절 ( "객체"의 정의) :
It is an unordered collection of properties each of which contains a primitive value, object, or function. A function stored in a property of an object is called a method.
I guess that means you cant rely on the properties being enumerated in a consistent order across JavaScript implementations. (It would be bad style anyway to rely on implementation-specific details of a language.)
If you want your order defined, you will need to implement something that defines it, like an array of keys that you sort before accessing the object with it.
The elements of an object that for/in enumerates are the properties that don't have the DontEnum flag set. The ECMAScript, aka Javascript, standard explicitly says that "An Object is an unordered collection of properties" (see http://www.mozilla.org/js/language/E262-3.pdf section 8.6).
It's not going to be standards conformant (i.e. safe) to assume all Javascript implementations will enumerate in declaration order.
Iteration order is also confused with respect to deleting of properties, but in this case with IE only.
var obj = {};
obj.a = 'a';
obj.b = 'b';
obj.c = 'c';
// IE allows the value to be deleted...
delete obj.b;
// ...but remembers the old position if it is added back later
obj.b = 'bb';
for (var p in obj) {
alert(obj[p]); // in IE, will be a, bb, then c;
// not a, c, then bb as for FF/Chrome/Opera/Safari
}
The desire for changing the spec to fix the iteration order seems to be quite a popular desire among developers if the discussion at http://code.google.com/p/v8/issues/detail?id=164 is any indication.
in IE6, the order is not guaranteed.
주문을 신뢰할 수 없습니다. Opera와 Chrome은 모두 정렬되지 않은 속성 목록을 반환합니다.
<script type="text/javascript">
var username = {"14719":"A","648":"B","15185":"C"};
for (var i in username) {
window.alert(i + ' => ' + username[i]);
}
</script>
위의 코드는 Opera의 B, A, C 및 Chrome의 C, A, B를 보여줍니다.
이것은 그 자체로 질문에 대답하지 않지만 기본 문제에 대한 해결책을 제공합니다.
보존 순서에 의존 할 수 없다고 가정하면 키와 값을 속성으로 갖는 객체 배열을 사용하지 않는 이유는 무엇입니까?
var myArray = [
{
'key' : 'key1'
'value' : 0
},
{
'key' : 'key2',
'value' : 1
} // ...
];
이제 키가 고유한지 확인해야합니다 (이것이 또한 중요하다고 가정 할 때) 직접 주소 지정 변경 사항 및 for (... in ...)는 이제 색인을 '키'로 리턴합니다.
> console.log(myArray[0].key);
key1
> for (let index in myArray) {console.log(myArray[index].value);}
0
1
펜보기
위해 주소 (...에 ...)를 들어 JDQ (가
@JDQ 에)
CodePen .
참고 URL : https://stackoverflow.com/questions/280713/elements-order-in-a-for-in-loop
'Programing' 카테고리의 다른 글
단일 페이지 응용 프로그램 : 장단점 (0) | 2020.05.11 |
---|---|
JavaScript에서 형식 지정을 사용하여 문자열을 날짜 / 시간으로 변환하려면 어떻게해야합니까? (0) | 2020.05.11 |
webpack으로 moment.js가 로캘을로드하지 못하게하는 방법은 무엇입니까? (0) | 2020.05.11 |
파이썬에서 모듈 전체 변수를 만드는 방법? (0) | 2020.05.11 |
github에 커밋하기 전에 readme.md 파일이 어떻게 보이는지 어떻게 테스트합니까? (0) | 2020.05.11 |