developer tip

자바 스크립트에서 배열을 배열로 스플 라이스하는 더 좋은 방법

copycodes 2020. 11. 29. 11:52
반응형

자바 스크립트에서 배열을 배열로 스플 라이스하는 더 좋은 방법


자바 스크립트의 다른 배열에 배열을 연결하는 것보다 더 좋은 방법이 있습니까?

var string = 'theArray.splice('+start+', '+number+',"'+newItemsArray.join('","')+'");';
eval(string);

적용사용 하여 평가를 피할 수 있습니다 .

var args = [start, number].concat(newItemsArray);
Array.prototype.splice.apply(theArray, args);

적용 기능, 예를 들면, 어레이로서 제공되고, 주어진 컨텍스트와 인수를, 다른 함수를 호출하는데 사용된다 :

전화하면 :

var nums = [1,2,3,4];
Math.min.apply(Math, nums);

적용 기능이 실행됩니다.

Math.min(1,2,3,4);

업데이트 : ES6 버전

ES6로 코딩한다면 "확산 연산자"(...)를 사용할 수 있습니다.

array.splice(index, 0, ...arrayToInsert);

스프레드 연산자에 대한 자세한 내용은 mozilla 문서를 참조하십시오 .

'오래된'ES5 방식

최상위 답변을 함수로 래핑하면 다음과 같이 표시됩니다.

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
}

다음과 같이 사용합니다.

var arr = ["A", "B", "C"];
insertArrayAt(arr, 1, ["x", "y", "z"]);
alert(JSON.stringify(arr)); // output: A, x, y, z, B, C

이 jsFiddle에서 확인할 수 있습니다. http://jsfiddle.net/luisperezphd/Wc8aS/


이 질문은 정말 오래되었지만 ES6에서는 스프레드 연산자를 사용하여이 작업을 수행하는 더 간단한 방법이 있습니다.

sourceArray.splice(index, 0, ...insertedArray)

브라우저에서 컴파일되지 않은 자바 스크립트를 사용하는 경우 https://kangax.github.io/compat-table/es6/#test-spread_(...)_operator 에서 대상 브라우저에서 지원되는지 확인 하세요 .


또한 이것은 주제에서 약간 벗어난 것일 수 있지만 원래 배열을 수정하고 싶지 않거나 수정해야하지만 대신 새 배열을 사용할 수있는 경우 다음 방법을 고려하십시오.

mergedArray = sourceArray.slice(0, index).concat(insertedArray, sourceArray.slice(index))

splice 방법과 거의 동일한 것을 원한다면 Array 프로토 타입에 이러한 함수를 추가 할 수도 있습니다.

Array.prototype.spliceArray = function(index, n, array) {
    return Array.prototype.splice.apply(this, [index, n].concat(array));
}

그러면 사용법은 다음과 같습니다.

var array = ["A","B","C","","E","F"];

array.splice(3,1,"D");
// array is ["A","B","C","D","E","F"]

array.spliceArray(3,3,["1","2","3"]);
// array is ["A","B","C","1","2","3"]

여기에서 실제 동작을 확인하세요 : http://jsfiddle.net/TheMadDeveloper/knv2f8bb/1/

몇 가지 참고 사항 :

  • splice함수는 배열을 직접 수정하지만 스 플라이 싱 된 배열이 아닌 제거 된 요소의 배열을 반환합니다.
  • 일반적으로 핵심 자바 스크립트 클래스를 확장하는 것은 권장되지 않지만 대부분의 표준 프레임 워크에서는 비교적 무해합니다.
  • 확장 Array은 ImageData 데이터 Uint8ClampedArray와 같은 특수 배열 클래스가 사용되는 경우 작동하지 않습니다.

splice.apply와 관련된 위의 답변은 하나의 라이너에 배열을 삽입하면 큰 배열의 스택 오버플로에서 스택이 날아갑니다. 여기에서 예를 참조하십시오. http://jsfiddle.net/gkohen/u49ku99q/ 원래 배열의 삽입 된 부분과 나머지 부분의 각 항목을 슬라이스하고 밀어 넣어야 작동 할 수 있습니다. 바이올린 참조 : http://jsfiddle.net/gkohen/g9abppgy/26/

Array.prototype.spliceArray = function(index, insertedArray) {
   var postArray = this.splice(index);
   inPlacePush(this, insertedArray);
   inPlacePush(this, postArray);

   function inPlacePush(targetArray, pushedArray) {
// Not using forEach for browser compatability
       var pushedArrayLength = pushedArray.length;
       for (var index = 0; index < pushedArrayLength; index++) {
           targetArray.push(pushedArray[index]);
       }
   }
}

There are a lot of clever answers here, but the reason you use splice is so that it puts the elements into the current array without creating another. If you have to create an array to concat() against so you can use apply() then you're creating 2 additional trash arrays! Sorta defeats the whole purpose of writing esoteric Javascript. Besides if you don't care about that memory usage stuff (and you should) just dest = src1.concat(src2); it is infinitely more readable. So here's is my smallest number of lines while staying efficient answer.

for( let item of src ) dest.push( item );

Or if you'd like to polyfill it and have a little better browser support back:

src.forEach( function( x ) { dest.push(x); });

I'm sure the first is more performant (it's a word ;), but not supported in all browsers out there in the wild.


If you don't want to concatenate inserting items to first two parameters of Array.splice(), an elegant way is to use Function.bind() and Function.apply() together.

theArray.splice.bind(null, startIndex, deleteCount).apply(newItemsArray);

I wanted to have a function which would take only part of the source array so I have mine slightly different based off CMS's answer

function spliceArray(array, index, howmany, source, start, end) {
    var arguments;
  if( source !== undefined ){
    arguments = source.slice(start, end);
    arguments.splice(0,0, index, howmany);
  } else{
   arguments = [index, howmany];
  }
    return Array.prototype.splice.apply(array, arguments)
}

Array.prototype.spliceArray = function(index, howmany, source, start, end) {
    return spliceArray(this, index, howmany, source, start, end);
}

You can see it at: https://jsfiddle.net/matthewvukomanovic/nx858uz5/

참고URL : https://stackoverflow.com/questions/1348178/a-better-way-to-splice-an-array-into-an-array-in-javascript

반응형