programing

배열에서 맵()을 자바스크립트로 역순으로 사용하는 방법이 있습니까?

easyjava 2023. 10. 1. 23:08
반응형

배열에서 맵()을 자바스크립트로 역순으로 사용하는 방법이 있습니까?

사용하고 싶습니다.map()자바스크립트 배열에서 작동하지만 역순으로 작동했으면 좋겠습니다.

그 이유는 Meteor 프로젝트에서 적층된 React 구성요소를 렌더링하고 있으며, 최상위 요소를 먼저 렌더링하고 나머지는 아래 이미지를 로드하고 싶기 때문입니다.

var myArray = ['a', 'b', 'c', 'd', 'e'];
myArray.map(function (el, index, coll) {
    console.log(el + " ")
});

인쇄물로 만들다a b c d e, 하지만 저는 지도가 인쇄되어 있으면 좋겠습니다.e d c b a.

어떻게 하면 되죠?

원래 배열을 되돌리고 싶지 않다면, 그 배열을 얕게 복사한 다음 거꾸로 배열의 지도를 만들면 됩니다.

myArray.slice(0).reverse().map(function(...

업데이트:

myArray.toReversed().map(()=>{...});

자바스크립트의 상태는 제 원래 답변 이후로 발전했습니다.Array.toRversed()는 이제 대부분의 환경에서 지원되며, 원본을 변경하지 않고 원래 배열에 대한 매핑을 거꾸로 표현할 수 있는 보다 현대적이고 깨끗한 방법입니다.

수학을 사용합니다.index제공된 것을 사용하지 않고 역순으로 요소에 접근하기 위해 매핑 기능에 제공됩니다.val:

myArray.map((val, index) => myArray[myArray.length - 1 - index]);

이는 O(n)이며 입력 배열을 변형하거나 복사하지 않습니다.

매핑 함수에 대한 세 번째 매개 변수는 기본 수집이므로, 이는 또한 폐쇄를 통해 참조할 필요를 피할 수 있습니다.

myArray.map((val, index, array) => array[array.length - 1 - index]);

사용가능Array.prototype.reduceRight()

var myArray = ["a", "b", "c", "d", "e"];
var res = myArray.reduceRight(function (arr, last, index, coll) {
    console.log(last, index);
    return (arr = arr.concat(last))
}, []);
console.log(res, myArray)

명명된 콜백 기능 포함

const items = [1, 2, 3]; 
const reversedItems = items.map(function iterateItems(item) {
  return item; // or any logic you want to perform
}).reverse();

속기(이름있는 콜백 함수 없음) - 화살표 구문, ES6

const items = [1, 2, 3];
const reversedItems = items.map(item => item).reverse();

결과는 이렇습니다.

enter image description here

당신은 단지 추가하기만 하면 됩니다..slice(0).reverse()전에.map()

students.slice(0).reverse().map(e => e.id)

또 다른 해결책은 다음과 같습니다.

const reverseArray = (arr) => arr.map((_, idx, arr) => arr[arr.length - 1 - idx ]);

기본적으로 배열 인덱스 작업을 수행합니다.

저는 맵리버스 함수를 한 번 작성한 후 사용하는 것을 선호합니다.또한 배열을 복사할 필요가 없습니다.

function mapReverse(array, fn) {
    return array.reduceRight(function (result, el) {
        result.push(fn(el));
        return result;
    }, []);
}

console.log(mapReverse([1, 2, 3], function (i) { return i; }))
// [ 3, 2, 1 ]
console.log(mapReverse([1, 2, 3], function (i) { return i * 2; }))
// [ 6, 4, 2 ]

제 생각에는.reverse()핵심을 찌르다map작동 중입니다.

tbl_products
  .map((products) => (
    <div
      key={products.pro_id}
      class="my-1 px-1 w-full md:w-1/2 lg:my-4 lg:px-4 lg:w-1/4 transform transition duration-500 hover:scale-105"
    >
      <article class="overflow-hidden rounded-lg border shadow">
        <a href="#">
          <img
            alt="Placeholder"
            class="block h-auto w-full px-5 pt-3"
            src={products.product_img}
          />
        </a>
      </article>
    </div>
  ))
  .reverse();

저 같은 경우는 효과가 있습니다.

다음은 O(n)이면서 다른 솔루션보다 효율적인 TypeScript 솔루션입니다. 어레이를 두 번 실행하지 않도록 하여 다음과 같습니다.

function reverseMap<T, O>(arg: T[], fn: (a: T) => O) {
   return arg.map((_, i, arr) => fn(arr[arr.length - i - 1]))
}

자바스크립트의 경우:

const reverseMap = (arg, fn) => arg.map((_, i, arr) => fn(arr[arr.length - 1 - i]))

// Or 

function reverseMap(arg, fn) {
    return arg.map((_, i, arr) => fn(arr[arr.length - i - 1]))
}

할수있습니다myArray.reverse()첫번째.

var myArray = ['a', 'b', 'c', 'd', 'e'];
myArray.reverse().map(function (el, index, coll) {
    console.log(el + " ")
});

먼저 배열의 복사본을 얕게 만든 다음 복사본에 해당 기능을 사용해야 합니다.

[...myArray].reverse().map(function(...
function mapRevers(reverse) {
    let reversed = reverse.map( (num,index,reverse) => reverse[(reverse.length-1)-index] );
    return reversed;
}

console.log(mapRevers(myArray));

I 배열을 전달하여 반전을 매핑하고 함수에서 반전 배열을 반환합니다.맵 cb에서 단순히 인덱스 카운트가 10(길이)에서 1로 전달된 배열로 값을 가져옵니다.

var myArray = ['a', 'b', 'c', 'd', 'e'];
var reverseArray = myArray.reverse()
reverseArray.map(function (el, index, coll) {
    console.log(el + " ")
});

reducers state라고 하자의 불변 배열을 사용하는 경우 적용할 수 있습니다..reverse()처음에 다음과 같이 복사를 함으로써.

const reversedArray = [...myArray].reverse();
//where myArray is a state variable

//later in code
reversedArray.map((item, i)=>doStuffWith(item))

코드 조각에 reverse()를 추가합니다.

YourData.reverse().map(...)

이 경우 원래 배열이 변형되므로 문제가 될 수 있습니다.

오래된 질문이지만, 새로운 시청자들에게는 이것이 지도를 사용하여 배열을 뒤집는 가장 좋은 방법입니다.

var myArray = ['a', 'b', 'c', 'd', 'e'];
[...myArray].map(() => myArray.pop());

언급URL : https://stackoverflow.com/questions/36415904/is-there-a-way-to-use-map-on-an-array-in-reverse-order-with-javascript

반응형