programing

어레이 엔트리를 코드 한 줄의 확산 구문으로 바꾸시겠습니까?

elseif 2023. 3. 5. 09:33

어레이 엔트리를 코드 한 줄의 확산 구문으로 바꾸시겠습니까?

...확산 구문을 사용하여 반응 상태 배열의 항목을 바꿉니다.이 방법은 다음과 같습니다.

let newImages = [...this.state.images]
newImages[4] = updatedImage
this.setState({images:newImages})

이것을 한 줄의 코드로 할 수 있을까요?이런 거?(이것은 분명히 효과가 없습니다.)

this.setState({images: [...this.state.images, [4]:updatedImage})

Array.slice 사용

this.setState({
  images: [
    ...this.state.images.slice(0, 4),
    updatedImage,
    ...this.state.images.slice(5),
  ],
});

Edit from original post: 슬라이스 방식의 두 번째 파라미터에서 3o a 4를 변경하였습니다.두 번째 파라미터는 마지막으로 유지된 어레이의 멤버를 가리키고 있기 때문에 원래 질문에 올바르게 답변합니다.

카피 프로포절별 변경 어레이가 널리 지원되면(3단계에서 JavaScript 엔진으로 이행할 예정) 새로운 기능을 이용할 수 있습니다.with방법:

// Using a Stage 3 proposal, not widely supported yet as of Nov 17 2022
this.setState({images: this.state.images.with(4, updatedImage)});

그때까지는 다음 작업을 수행합니다.

this.setState({images: Object.assign([], this.state.images, {4: updatedImage}));

...하지만 임시 객체(마지막에 있는 객체)를 포함합니다.그래도, 단 하나의 임시 객체...이렇게 하면slice어레이를 분산시키면 몇 가지 일시적인 오브젝트가 더 필요합니다.(2개의 어레이는slice, 반복기, 반복기 호출에 의해 작성된 결과 객체next기능하다...[handle] 등)을 클릭합니다.

일반 JS 어레이는 실제로1 어레이가 아니기 때문에(물론 최적화의 영향을 받지만) 일부 특수 기능이 있는 객체이기 때문에 작동합니다.이러한 "색인"은 실제로 특정 조건2 충족하는 속성 이름입니다.그래서 저기, 우린 흩어져서this.state.images새로운 배열로, 그것을 전달한다.Object.assign타겟으로서, 그리고 기부를 한다.Object.assign성질이 있는 물건"4"(예, 이것은 문자열이 되지만 숫자로 쓸 수 있습니다) 갱신할 값을 지정합니다.

라이브 예:

const a = [0, 1, 2, 3, 4, 5, 6, 7];
const b = Object.assign([], a, {4: "four"});
console.log(b);

이 경우,4변수일 수 있습니다.괜찮습니다.계산된 속성 이름을 사용할 수 있습니다(ES2015의 새로운 기능).

let n = 4;
this.setState({images: Object.assign([], this.state.images, {[n]: updatedImage}));

주의:[]주위에n.

라이브 예:

const a = [0, 1, 2, 3, 4, 5, 6, 7];
const index = 4;
const b = Object.assign([], a, {[index]: "four"});
console.log(b);


1 공개:내 빈약한 블로그에 올린 글이야

2 글머리 기호 목록 다음에 나오는 두 번째 단락입니다.

정수 인덱스는 표준 숫자 문자열(7.1.16 참조)이며 숫자 값이 +0 또는 양의 정수인 String53 값 속성 키입니다.배열 인덱스는 숫자 i가 +0 µ i < 2-1인32 정수 인덱스입니다.

★★★★★★★★★★★★★★★★★.Object.assigncreate-the-array-the-update-index-4와 같은 합니다.

맵을 사용할 수 있습니다.

const newImages = this.state.images
  .map((image, index) => index === 4 ? updatedImage : image)

를 오브젝트/FONT CHANGE/FONT CHANGE/FONT CHANGE:])로 변환할 수 있습니다....array1 「」, 「」, 「 」[1]:"seven" 「어레이 ).Object.values

array1 = ["one", "two", "three"];
array2 = Object.values({...array1, [1]:"seven"});
console.log(array1);
console.log(array2);

비원라이너에 대해 제가 직접 설명하겠습니다.

 const wantedIndex = 4;
 const oldArray = state.posts; // example

 const updated = {
     ...oldArray[wantedIndex], 
     read: !oldArray[wantedIndex].read // attributes to change...
 } 

 const before = oldArray.slice(0, wantedIndex); 
 const after = oldArray.slice(wantedIndex + 1);

 const menu = [
     ...before,  
     updated,
     ...after
 ]

@Bardia Rastin 솔루션을 참조했는데, 이 솔루션의 인덱스 값이 잘못되어 있습니다(인덱스 3의 아이템은 대체되지만 4는 대체되지 않습니다).

인덱스 값, 인덱스가 있는 항목을 대체하려면 다음과 같이 대답해야 합니다.

this.setState({images: [...this.state.images.slice(0, index), updatedImage, ...this.state.images.slice(index + 1)]})

this.state.images.slice(0, index)새로운 배열의 항목은 0부터 인덱스 - 1까지입니다(인덱스는 포함되지 않습니다).

this.state.images.slice(index)새 배열에 인덱스에서 시작하는 항목과 이후 항목이 있습니다.

인덱스 4의 항목을 올바르게 대체하려면 다음과 같이 답해야 합니다.

this.setState({images: [...this.state.images.slice(0, 4), updatedImage, ...this.state.images.slice(5)]})

먼저 인덱스를 찾습니다.여기에서는 이미지 문서 ID docId를 그림으로 사용합니다.

const index = images.findIndex((prevPhoto)=>prevPhoto.docId === docId)
this.setState({images: [...this.state.images.slice(0,index), updatedImage, ...this.state.images.slice(index+1)]})

나는 스프레드 연산자를 많이 사용해 보았다.splice()를 사용하면 메인 배열이 변경된다고 생각합니다.그래서 제가 발견한 솔루션은 어레이를 새로운 변수로 복제하고 확산 연산자를 사용하여 어레이를 분할하는 것입니다.내가 사용한 예.

var cart = [];

function addItem(item) {
    let name = item.name;
    let price = item.price;
    let count = item.count;
    let id = item.id;

    cart.push({
        id,
        name,
        price,
        count,
    });

    return;
}

function removeItem(id) {
    let itemExist = false;
    let index = 0;
    for (let j = 0; j < cart.length; j++) {
        if (cart[j].id === id) { itemExist = true; break; }
        index++;
    }
    if (itemExist) {
        cart.splice(index, 1);
    }
    return;
}

function changeCount(id, newCount) {
    let itemExist = false;
    let index = 0;
    for (let j = 0; j < cart.length; j++) {
        console.log("J: ", j)
        if (cart[j].id === id) {
            itemExist = true;
            index = j;
            break;
        }
    }
    console.log(index);
    if (itemExist) {
        let temp1 = [...cart];
        let temp2 = [...cart];
        let temp3 = [...cart];
        cart = [...temp1.splice(0, index),
            {
                ...temp2[index],
                count: newCount
            },
            ...temp3.splice(index + 1, cart.length)
        ];
    }

    return;
}

addItem({
    id: 1,
    name: "item 1",
    price: 10,
    count: 1
});
addItem({
    id: 2,
    name: "item 2",
    price: 11,
    count: 1
});
addItem({
    id: 3,
    name: "item 3",
    price: 12,
    count: 2
});
addItem({
    id: 4,
    name: "item 4",
    price: 13,
    count: 2
});

changeCount(4, 5);
console.log("AFTER CHANGE!");
console.log(cart);

언급URL : https://stackoverflow.com/questions/45673783/replace-array-entry-with-spread-syntax-in-one-line-of-code