Recent posts

Recent comments

Archive

Calender

«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31

[ Javascript ] slice() of array


최종 수정일 ( Last modified date ) : 2017. 05. 03.


배열의 slice()는 해당 배열에서 원하는 부분만 잘라오고 싶을 때 사용한다.
slice()는 잘라온 부분을 새 배열에 담아준다.

The slice() of array is used when you want to slice the desired part of that array.
The sliced part is inserted into a new array.





기본 사용법 ( How to use )


잘라올 부분의 시작과 끝을 지정해주지 않으면, 그 배열의 처음부터 끝까지 잘라온다.
즉, 해당 배열을 통째로 복사해온다.

If you do not specify the beginning & end of the slice, it will be sliced from beginning to end.
That is, the array is copied.


 
<button onclick="testing()"> testing </button> <button onclick="example()"> example </button>

<p id="demo1"> </p>

array : <span id="demo2"> </span><br />
copy : <span id="demo3"> </span>

<script type="text/javascript">

var array = [ "Banana", "Orange", "Lemon", "Apple", "Mango" ]; 

var copy = array.slice(); 

function testing () {  demo1.innerHTML  = copy;  } 

function example () { 

    array.push( "Peach" ); 
    copy.push( "Grape" ); 

    demo2.innerHTML = array.join( ", " ); 
    demo3.innerHTML = copy.join( ", " ); 
} 
</script>
 

위 예문에서 보듯이,
잘라온 배열이 바뀌어도, 원본 배열은 바뀌지 않는다.
마찬가지로, 원본 배열이 바뀐다해도 잘라온 배열은 바뀌지 않는다.

As shown in the above example,
even if the sliced array changes, the original array does not change.
Similarly, even if the original array changes, the sliced array does not change.




어떤 객체(object)를 배열에 담고서, slice를 이용하여 그 배열을 복사한 경우,
복사된 배열 안에 들어간 객체의 값을 바꿔주게 되면, 원본 배열에 들어있는 값도 바뀌게 된다.
어찌보면, 당연한 얘기겠지만... ─.─;;

When you put some object in array and copy that array, using slice(),
if you change the object's value in the copied array,
the object's value in the original array will also change, of course.


 
<button onclick="testing()"> Click me </button><br />

person.name : <span id="demo1"> </span><br />
array[ 0 ].name : <span id="demo2"> </span><br />
copy[ 0 ].name : <span id="demo3"> </span>

<script type="text/javascript">

var person = { name: "Tonks", gender: "Female" }; 

var array = [ person ]; 

var copy = array.slice(); 

function testing () { 

    copy[ 0 ].name = "Alice"; 

    demo1.innerHTML = person.name; 
    demo2.innerHTML = array[ 0 ].name; 
    demo3.innerHTML = copy[ 0 ].name; 
} 
</script>
 


slice()의 괄호 안에 입력하는 첫번째 숫자는 slice를 시작할 위치값이다.
The first number in parentheses of slice(), is the position to begin that sliced.


 
<button onclick="testing()"> Click me </button>

<p id="demo1"> </p>
<p id="demo2"> </p>

<script type="text/javascript">

var array = [ ]; 
      array[ 0 ] = "Banana"; 
      array[ 1 ] = "Orange"; 
      array[ 2 ] = "Lemon"; 
      array[ 3 ] = "Apple"; 
      array[ 4 ] = "Mango"; 

demo1.innerHTML = array.join( ", " ); 

function testing () { 

    var slice = array.slice( 1 ); 

    demo2.innerHTML = slice.join( ", " ); 
} 
</script>
 


두번째 숫자는 slice를 끝낼 위치값이다.
주의할 점은, 마지막 위치에 들어있는 값은 포함이 안된다는 것이다.

The second number is the position to end that sliced.
Note that the value in the end position is not included.


 
<button onclick="testing()"> Click me </button>

<p id="demo"> </p>

<script type="text/javascript">

var array = [ ]; 
      array[ 0 ] = "Banana"; 
      array[ 1 ] = "Orange"; 
      array[ 2 ] = "Lemon"; 
      array[ 3 ] = "Apple"; 
      array[ 4 ] = "Mango"; 

function testing () { 

    var slice = array.slice( 1, 3 ); 

    demo.innerHTML = slice.join( ", " ); 
} 
</script>
 


Array.prototype.slice.call


배열의 속성(Array.prototype)중 하나인 slice를 불러와서(call), 배열이 아닌 것들을 배열로 바꿔줄 수도 있다.
물론, 값이 null이나 undefined인 것은 사용할 수 없다.

You can call an slice of Array.prototype, to convert non-array into array.
Of course, it must not be "null" or "undefined".


사용방법은 아래와 같다. How to use is as follows.


Array.prototype.slice.call() 

또는 (Or, ) 

[ ].slice.call() 

 
<button onclick="testing()"> Click me </button>

<p id="demo"> </p>

<script type="text/javascript">
function getArguments () { 

    return Array.prototype.slice.call( arguments ); 
} 

function testing () { 

    var array = getArguments( "Banana", "Orange", "Lemon" ); 

    demo.innerHTML = array.join( ", " ); 
} 
</script>
 

 
<button onclick="testing()"> Click me </button><br />

string : <span id="demo1"> </span><br />
object : <span id="demo2"> </span>

<script type="text/javascript">
function convertToArray ( obj ) {  return [ ].slice.call( obj );  } 

function testing () { 

    var string = "Banana"; 

    var object = { 0: "Orange", 1: "Lemon", 2: "Apple", length: 3 }; 

    demo1.innerHTML = convertToArray( string ).join( ", " ); 
    demo2.innerHTML = convertToArray( object ).join( ", " ); 
} 
</script>
 

위의 예문에서,
새 배열에 담기는 것은 그 객체(object)가 아니라, 객체에 들어있는 항목의 값들이다.
따라서, 새 배열의 값이 바뀐다해도, 기존 객체의 값은 바뀌지 않는다.

In the above example,
The values that included in new array, are the item values in object, not object.
Therefore, even if the value in new array changes, the item value in the object does not change.


 
<button onclick="testing()"> Click me </button><br />

object[ 0 ] : <span id="demo1"> </span><br />
valueList[ 0 ] : <span id="demo2"> </span>

<script type="text/javascript">
function testing () { 

    var object = { 0: "Orange", 1: "Lemon", 2: "Apple", length: 3 }; 

    var valueList = [ ].slice.call( object ); 

    valueList[ 0 ] = "Mango"; 

    demo1.innerHTML = object[ 0 ]; 
    demo2.innerHTML = valueList[ 0 ]; 
} 
</script>
 


배열의 slice를 불러오면, 어떤 값을 넣어주던지간에, 새로운 배열이 만들어지기는 한다.
하지만, 아래 예문에서는, 아무 값도 들어있지 않은 빈 배열이 만들어진다.

When you call "slice" of Array, no matter what the given value, a new array is created.
In the following example, an empty array is created.


 
<button onclick="testing()"> testing </button><br />

number : <span id="demo1"> </span><br />
objA : <span id="demo2"> </span><br />
objB : <span id="demo3"> </span>

<script type="text/javascript">

var sliceOfArray = [ ].slice; 

function testing () { 

    var number = 1234; 

    var objA = { 0: "Orange", 1: "Lemon", 2: "Apple" }; 

    var objB = { name: "Tonks", gender: "Female" }; 

    demo1.innerHTML = sliceOfArray.call( number ).join( ", " ); 
    demo2.innerHTML = sliceOfArray.call( objA ).join( ", " ); 
    demo3.innerHTML = sliceOfArray.call( objB ).join( ", " ); 
} 
</script>
 

objA에는 length가 없고,
objB에는 length도, 위치(index)가 지정된 것도 없기 때문이다.
한마디로, 객체(object)의 생김새가 배열과 닮은꼴이어야 한다는 말이다. (흔히들, "유사 배열 객체"라고 부르는 것들)

objA does not contain length item.
objB does not contain length nor an index item.
It means, an object must be "array-like" object.




Polyfill


간혹, 익스플로러(IE) 8이나 9와 같은 오래된 브라우저에서 slice를 사용할 때,
문자열(string)을 배열로 바꾸거나,
document.getElementsByTagName( "*" )에서 일부를 가져오려 할 경우,
제대로 실행되지 않을 때가 있다.

따라서, Array.prototype.slice를 아래처럼 바꿔주어야 한다.

Sometimes, in older browsers (like IE 8 or 9),
when you try to convert string into array, or to slice a part in document.getElementsByTagName( "*" )
it does not work properly.

So, you must change Array.prototype.slice, as below.


 
<script type="text/javascript">
/* 
 * source : https://tonks.tistory.com/186#_javascript_array_slice
 * last modified date : 2017. 05. 07. 
 */ 
(function () { 

    var arrSlice = [ ].slice; 

    try { 
            arrSlice.call( document.getElementsByTagName( "*" ), 1 ); 
            return; 
    } 
    catch ( error ) { } 

    var objToStr = Object.prototype.toString; 
    var min = Math.min; 
    var max = Math.max; 

    Array.prototype.slice = function slice ( begin, end ) { 

        if ( this == null ) { 
                var error = new TypeError( "Array.prototype.slice called on null or undefined" ); 
                      error.description = error.name + ": " + error.message; 

                throw error; 
        } 

        var len = this.length || 0; 

        begin = Number( begin ) || 0; 
        if ( begin < 0 ) begin = max( 0, len + begin ); 

        end = ( typeof end == "undefined" || end == null ) ? len : Number( end ); 
        end = ( end < 0 ) ? end + len : min( end, len ); 

        if ( objToStr.call( this ) === "[object Array]" ) return arrSlice.call( this, begin, end ); 

        var x = 0; 
        var lastIndex = end - begin; 
        var copy = [ ]; 

        var isString = ( this.charAt ) ? true : false; 

        for ( x ; x < lastIndex; x++ ) { 
                copy[ x ] = ( isString ) ? this.charAt( begin + x ) : this[ begin + x ]; 
        } 

        return copy; 
    }; 

    // Array.prototype.slice.toString = function toString () { return "function slice () {\n    [native code]\n}" }; 
}()); 
</script>
 


이 내용이 도움이 되셨다면, 아래의 하트 버튼을 눌러주세요 *^^*
If this article is helpful to you, please click the heart button below. *^^*