2017-12-26 4 views
0

부울 변수에 따라 배열에서 첫 번째 (또는 마지막) 요소를 삭제하는 코드 조각이 있습니다. 나는 다음과 같이 수행javascript 메서드 array.shift() undefined를 반환합니다.

{... 
console.log("length before " + waypoints.length) 
waypoints = this.deleteWaypoint(waypoints) 
console.log("length after " + waypoints.length) 
...} 

deleteWaypoint(waypoints){ 
if (this.first){ 
    this.first = false; 
    return waypoints.shift() 
} else { 
    this.first = true; 
    return waypoints.pop() 
} 
} 

waypoints 특정 길이가 첫 번째 로그 인쇄, 그럼 내가 요소를 삭제하는 방법을 호출하고 두 번째 로그 인쇄는 length after undefined 때. "First"는 참으로 초기화 된 전역 변수입니다. 왜 그럴까요?

+0

즉시 배열이 비어로, 당신이 얻을 정의되지 않은, ([여기]를 설명 https://developer.mozilla.org/en-US/ docs/Web/JavaScript/Reference/Global_Objects/Array/shift) – lumio

+2

['Array.prototype.shift'] (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array)/shift) : _ "shift() 메서드는 배열 **에서 첫 번째 요소를 제거하고 제거 된 요소 **를 반환합니다."_ – Andreas

+0

return 문을 'deleteWaypoint'의'return waypoints '로 업데이트합니다. –

답변

2

변화에 따라 아래의 기능 :

var waypoints = [1,2,3,4,5,6,7,8,9,0]; 
 

 
var deleteWaypoint = (waypoints)=>{ 
 
if (this.first){ 
 
    this.first = false; 
 
    waypoints.shift(); 
 
    return waypoints 
 
} else { 
 
    this.first = true; 
 
    waypoints.pop() 
 
    return waypoints 
 
} 
 
} 
 

 
console.log("length before " + waypoints.length) 
 
waypoints = deleteWaypoint(waypoints) 
 
console.log("length after " + waypoints.length)
이 나를 위해 완벽하게 잘 작동

0

;

var deleteWaypoint = function (waypoints) { 
    if (this.first) { 
    this.first = false; 
    waypoints.shift() 
    } else { 
    this.first = true; 
    waypoints.pop() 
    } 
}; 

this.first = true 
var waypoints = [1,2,3,4,5]; 
console.log("length before " + waypoints.length); 
deleteWaypoint(waypoints) 
console.log("length after " + waypoints.length); 

Array.shift()는 배열의 참조가되지 않습니다 제거 된 요소에 재 할당지고,

waypoints = this.deleteWaypoint(waypoints) 

질문에 게시 코드에서 복사 아래 라인에서 제거 된 배열을 반환 배열 및 길이 속성을 가지고 있지 않으므로 반환되지 않음

0

그래, 그 때문에 올바른 그 return waypoints.shift()은 배열에서 삭제 된 단일 요소를 반환합니다. 그런 다음 waypoints.shift() , 먼저 같이 할 수 return waypoints

관련 문제