2012-10-25 2 views
-1

나는 x 값의 양을 가진 자바 스크립트 배열을 가지고 있습니다.배열의 첫 번째 요소를 복사하고 마지막 배열을 대체하십시오.

어떻게 배열의 마지막 요소를 첫 번째 요소로 바꿀 수 있습니까? (위치를 전환하지만 마지막 어레이를 제거하고 최종 위치에서 제 넣지)

예 :

초기 배열 : 9, 14, 23, 12, 1] 최종 배열 : 9 14 , 23, 12, 9]

+1

어떻게 해야할지 모르겠습니까? 첫 번째 멤버, 마지막 멤버를 참조하거나 과제를 수행합니까? –

+0

죄송합니다. 내 마음이 여기에 끼어 들었습니다. – mallix

답변

6
array[array.length-1] = array[0]; 

별로 알 필요가 없습니다. 우선은 JavaScript Array Object을 참조하십시오.

+0

고맙습니다. @Michal Klouda – mallix

0

배열에 대한 값을 사용할 수 있습니다! 희망이 도움이! :)

// replaces the last index of an array with the first. 
var replace = function(InputArray){ 
    //saves the first index of the array in var a 
    var a = InputArray[0]; 
    //removes the last index of the array 
    InputArray.pop; 
    //places a copy of the first index in the place where the last index was 
    InputArray.push(a); 
    //returns the array 
    return InputArray; 
} 
//call the function 
replace([9, 14, 23 ,12 ,1]); 
// result => [9, 14, 23, 12, 1, 9] 

//If you want, you can log it in the console! 
console.log(replace([9, 14, 23 ,12 ,1])); 
관련 문제