내부 및 외부 루프에서 별도의 변수를 사용해야합니다. 대신 내부 루프에 y
을 사용하면 정확한 답을 얻을 수 있습니다.
var bubbleSort = function (elements) {
//Loop through to the second to last index. By the time we get to the last index, its already //been compared with what’s in front of it
var hasHadChange;
for (var x = 0; x < elements.length - 1; x++) {
hasHadChange = false;
//Loop through to the second to last index.
for (y = 0; y < elements.length - 1; y++) {
//Check the current item(x) in the array plus the item next to current item (x+1), if its larger
if (elements[y] > elements[y + 1]) {
//Acknowledge there has been a change
hasHadChange = true;
//Swap the items around
var temp = elements[y];
elements[y] = elements[y + 1];
elements[y + 1] = temp;
//This continues until the largest value has bubbled to the right
}
}
}
return elements;
}
이 뒤에 그 이유는 변수 게양입니다.
변수가 선언되면 두 부분으로 나뉩니다. 한 부분이 범위의 맨 위로 이동하고 다른 부분은 위치에 유지됩니다. 이 코드에서 무슨 일이 있었는지입니다
function foo() {
var x = undefined; //Declaration of x is hoisted
var y = undefined; //Declaration of y is hoisted
if (false) {
x = 1; //Assignment still occurs where we intended
}
y = 1; //Assignment still occurs where we intended
}
: 같은 예를 들어,
function foo() {
if (false) {
var x = 1;
}
var y = 1;
}
보일 것이다. 두 루프에서 같은 변수를 사용하면 서로 다른 값을 덮어 씁니다. 따라서 결과.
ECMAScript standard 5.1에서 :
변수 문은 10.5에 정의 된대로 생성되는 변수를 선언합니다. 변수는 생성 될 때 undefined로 초기화됩니다. Initialiser가있는 변수에는 변수가 만들어 질 때가 아니라 VariableStatement가 실행될 때 AssignmentExpression 값이 할당됩니다.
자세한 내용은 this MDN doc을 참조하십시오. 토픽 var hoisting을 찾으십시오. 블록 레벨 범위가 let
를 사용
업데이트
, 당신은 두 루프의 변수 x
을 가질 수 있습니다. 당신은 모두 사이클에 대해 동일한 제어 변수 x
을 사용하는
var bubbleSort = function (elements) {
//Loop through to the second to last index. By the time we get to the last index, its already //been compared with what’s in front of it
var hasHadChange;
for (var x = 0; x < elements.length - 1; x++) {
hasHadChange = false;
//Loop through to the second to last index.
for (let x = 0; x < elements.length - 1; x++) {
//Check the current item(x) in the array plus the item next to current item (x+1), if its larger
if (elements[x] > elements[x + 1]) {
//Acknowledge there has been a change
hasHadChange = true;
//Swap the items around
var temp = elements[x];
elements[x] = elements[x + 1];
elements[x + 1] = temp;
//This continues until the largest value has bubbled to the right
}
}
}
return elements;
}
이상한 효과를 유발하는 두 루프에서 동일한 변수 이름 (x)을 사용하고 있습니다. 그들 중 하나를 변경하십시오. hasHadChange를 사용하지 않고 중요성을 파악하고 사용하십시오. – dsharew
빠른 답장을 보내 주셔서 감사합니다. ive는 x와 Y로 vars를 구분하지만, 여전히 루프가 끊어집니다. 어떤 순서로든 내 값을 반환해도 동일한 결과가 반환됩니다. –
그래서 위 코드를 새 것으로 업데이트하십시오. 다른 버그가 있는지보십시오. – dsharew