Javascript Array Concat이 작동하지 않습니다. 왜죠?
그래서 저는 이 jqueryui 위젯을 만들었습니다.그것은 제가 오류를 스트리밍할 수 있는 디브를 만듭니다.위젯 코드는 다음과 같습니다.
$.widget('ui.miniErrorLog', {
logStart: "<ul>", // these next 4 elements are actually a bunch more complicated.
logEnd: "</ul>",
errStart: "<li>",
errEnd: "</li>",
content: "",
refs: [],
_create: function() { $(this.element).addClass( "ui-state-error" ).hide(); },
clear: function() {
this.content = "";
for ( var i in this.refs )
$( this.refs[i] ).removeClass( "ui-state-error" );
this.refs = [];
$(this.element).empty().hide();
},
addError: function( msg, ref ) {
this.content += this.errStart + msg + this.errEnd;
if ( ref ) {
if ( ref instanceof Array )
this.refs.concat( ref );
else
this.refs.push( ref );
for ( var i in this.refs )
$( this.refs[i] ).addClass( "ui-state-error" );
}
$(this.element).html( this.logStart + this.content + this.logEnd ).show();
},
hasError: function()
{
if ( this.refs.length )
return true;
return false;
},
});
오류 메시지를 추가할 수 있으며, 오류 상태가 되는 페이지 요소에 대한 참조를 추가할 수 있습니다.대화 상자를 확인하는 데 사용합니다."addError" 메서드에서 단일 ID 또는 다음과 같은 ID 배열을 전달할 수 있습니다.
$( "#registerDialogError" ).miniErrorLog(
'addError',
"Your passwords don't match.",
[ "#registerDialogPassword1", "#registerDialogPassword2" ] );
하지만 ID 배열을 입력하면 작동하지 않습니다.문제는 다음 행에 있습니다(제 생각).
if ( ref instanceof Array )
this.refs.concat( ref );
else
this.refs.push( ref );
왜 그 콘캣은 작동하지 않는 거지?이 .refs 및 ref는 둘 다 배열입니다.그런데 왜 콘캣이 작동하지 않는 걸까요?
보너스: 제가 이 위젯에서 다른 멍청한 짓을 하고 있습니까?저는 처음이에요.
concat 메서드는 원래 배열을 변경하지 않으므로 다시 할당해야 합니다.
if ( ref instanceof Array )
this.refs = this.refs.concat( ref );
else
this.refs.push( ref );
다음과 같은 이유가 있습니다.
정의 및 사용
concat() 메서드는 둘 이상의 배열을 결합하는 데 사용됩니다.
이 메서드는 기존 배열을 변경하지 않고 조인된 배열의 값을 포함하는 새 배열을 반환합니다.
연결 결과를 사용자가 가지고 있는 어레이에 다시 할당해야 합니다.
콘스탄틴 디네브에서 확장하기
.concat()현재 개체에 추가되지 않으므로 다음 작업이 수행되지 않습니다.
foo.bar.concat(otherArray);
다음 작업을 수행합니다.
foo.bar = foo.bar.concat(otherArray);
=를 사용하여 어레이에 값을 다시 할당해야 합니다. 이 경우 연결된 값을 얻을 수 있습니다.
let array1=[1,2,3,4];
let array2=[5,6,7,8];
array1.concat(array2);
console.log('NOT WORK : array1.concat(array2); =>',array1);
array1= array1.concat(array2);
console.log('WORKING : array1 = array1.concat(array2); =>',array1);
dataArray = dataArray.concat(array2)
다른 사람들이 언급했습니다.this.refs.concat(ref);개체에 재할당할 수 있는 새 배열을 할당하고 반환합니다.this.refs = this.refs.concat(ref);.concat어느 인수 배열도 수정하지 않습니다.
그러나 여기서 더 정확한 것은 호출 배열에 요소를 추가하는 인플레이스(in-place)에 요소를 추가합니다.this.refs.push(ref);(재할당 안 함)=--push일반적으로 무시되는 새 배열 길이를 반환합니다.
여러 항목을 추가하는 경우push에서는 변수 인수를 사용할 수 있으므로 변수 인수 위에 배열을 펼 수 있습니다.
const arr = [0, 1, 2];
arr.push(3); // add one element
console.log(arr) // => [0, 1, 2, 3]
arr.push(4, 5); // add two elements
console.log(arr) // => [0, 1, 2, 3, 4, 5]
const toAdd = [6, 7, 8];
arr.push(...toAdd); // add an array
console.log(arr); // => [0, 1, 2, 3, 4, 5, 6, 7, 8]
concat재할당을 사용하여 유사한 결과를 생성할 수 있습니다.
let arr = [0, 1, 2];
arr = arr.concat(3); // reassign with one new element
console.log(arr) // => [0, 1, 2, 3]
arr = arr.concat(4, 5); // reassign with two new elements
console.log(arr) // => [0, 1, 2, 3, 4, 5]
const toAdd = [6, 7, 8];
arr = arr.concat(toAdd); // reassign with a new array added
console.log(arr); // => [0, 1, 2, 3, 4, 5, 6, 7, 8]
concat이 사용 사례에는 분명히 덜 최적이지만 특히 불변성이 필요할 때(예: React 상태로 작업할 때) 다른 사용자에게 유용합니다.
로 돌연변이를 일으키는 또 다른 기회.pushhandy는 인수를 변형시켜야 하는 함수에 있습니다.
const addOne = arr => { // contrived example
arr.push(1);
};
const arr = [];
addOne(arr);
console.log(arr); // => [1] as expected
const addOneBroken = arr => {
arr = arr.concat(1); // purely local reassignment!
};
addOneBroken(arr);
console.log(arr); // => still [1]
배열과 항목을 병합하는 또 다른 옵션은 concat과 유사한 스프레드 구문입니다.
let arr = [0, 1, 2];
const toAdd = [3, 4, 5];
const arr1 = [...arr, 3]; // add one item, similar to concat
console.log(arr1); // [0, 1, 2, 3]
const arr2 = [...arr, ...toAdd]; // add an array, similar to concat
console.log(arr2); // [0, 1, 2, 3, 4, 5]
arr = [-1, ...arr, 42, ...toAdd, 6, 7]; // build a new complex array and reassign
console.log(arr); // => [-1, 0, 1, 2, 42, 3, 4, 5, 6, 7]
위의 작업은 체인으로 수행할 수 있습니다.concat 전화 번호:
let arr = [0, 1, 2];
const toAdd = [3, 4, 5];
arr = [-1].concat(arr).concat(42).concat(toAdd).concat(6).concat(7);
console.log(arr); // => [-1, 0, 1, 2, 42, 3, 4, 5, 6, 7]
어레이가 있는 경우 다음 시간 동안에는push를 그냥 ....스프레드:
const arr = [0, 1, 2];
const toAdd = [3, 4, 5];
arr.push(toAdd);
console.log(arr); // => [0, 1, 2, [3, 4, 5]]
그concat메소드는 원래 배열을 변경하지 않으며 배열 파괴를 사용할 수 있습니다.
const numbers = [1,2,3,4];
const newNumbers = [5,6,7,8,9];
numbers.push(...newNumbers); // [1,2,3,4,5,6,7,8,9]
참고로 concat 함수를 사용할 때 정말로 mutable 배열을 사용하려면(mutable은 새 배열을 만들지 않고 기존 배열을 변형함) 해당 배열 인스턴스에 대해 concat 함수를 재할당할 수 있습니다.이것이 필요할 때 제가 한 일이 있습니다.
let myArray = [];
myArray.concat= function( toAdd){
if(Array.isArray(toAdd)){
for(let node of toAdd)
this.push(node);
}else
this.push(toAdd);
}
언급URL : https://stackoverflow.com/questions/12803604/javascript-array-concat-not-working-why
'programing' 카테고리의 다른 글
| 날짜 데이터 유형 기본값을 설정하는 방법은 무엇입니까? (0) | 2023.08.31 |
|---|---|
| JavaScript 개체의 속성을 계산하려면 어떻게 해야 합니까? (0) | 2023.08.31 |
| AJAX에서 중첩된 FormData 전송 (0) | 2023.08.31 |
| Docker CMD를 여러 번 사용하여 여러 서비스를 실행할 수 없는 이유는 무엇입니까? (0) | 2023.08.31 |
| 동적 입력 배열에 대한 null 값 삽입 (0) | 2023.08.31 |