programing

시퀀스에 대한 Python 'enumerate'와 동일한 ES6은 무엇입니까?

iphone6s 2023. 10. 4. 21:02
반응형

시퀀스에 대한 Python 'enumerate'와 동일한 ES6은 무엇입니까?

파이썬에는 다음과 같은 반복 기능이 내장되어 있습니다.(index, item)쌍들.

ES6에 어레이와 동등한 요소가 있습니까?그것은 무엇일까요?

def elements_with_index(elements):
    modified_elements = []
    for i, element in enumerate(elements):
         modified_elements.append("%d:%s" % (i, element))
    return modified_elements

print(elements_with_index(["a","b"]))
#['0:a', '1:b']

ES6와 동등한 수준(무포함)enumerate:

function elements_with_index(elements){
     return elements.map(element => elements.indexOf(element) + ':' + element);
 }

console.log(elements_with_index(['a','b']))
//[ '0:a', '1:b' ]

네, 있습니다. 확인해보세요.

const foobar = ['A', 'B', 'C'];

for (const [index, element] of foobar.entries()) {
  console.log(index, element);
}

배열.원형.지도

Array.prototype.map이미 콜백 절차의 두 번째 인수로 인덱스를 제공하고 있습니다...그리고 거의 모든 곳에서 지원됩니다.

['a','b'].map(function(element, index) { return index + ':' + element; });
//=> ["0:a", "1:b"]

저도 ES6 좋아해요.

['a','b'].map((e,i) => `${i}:${e}`)
//=> ["0:a", "1:b"]

게으름 피우다

하지만, 비단뱀의enumerate게으르고 그래서 우리도 그 특성을 본받아야 합니다.

function* enumerate (it, start = 0)
{ let i = start
  for (const x of it)
    yield [i++, x]
}

for (const [i, x] of enumerate("abcd"))
  console.log(i, x)

0 a
1 b
2 c
3 d

두번째 인수를 명시하면,start, 호출자가 인덱스 변환을 제어할 수 있습니다.

for (const [i, x] of enumerate("abcd", 100))
  console.log(i, x)
100 a
101 b
102 c
103 d

let array = [1, 3, 5];
for (let [index, value] of array.entries()) 
     console.log(index + '=' + value);

제가 무지하다면 실례지만(여기 자바스크립트 초보자인데) 그냥 사용해주시면 안되나요?forEach? 예:

function withIndex(elements) {
    var results = [];
    elements.forEach(function(e, ind) {
        results.push(`${e}:${ind}`);
    });
    return results;
}

alert(withIndex(['a', 'b']));

naomik의 답변도 있는데, 이 특정한 사용 사례에 더 적합한 답변입니다만, 저는 단지 지적하고 싶었습니다.forEach또한 계산에 들어맞습니다.

ES5+ 지원.

pythonic 제안합니다.enumerate배열 뿐만 아니라 모든 이터레이블에서 작동하며 파이썬과 같은 이터레이터를 반환하는 기능:

import {enumerate} from 'pythonic';

const arr = ['a', 'b'];
for (const [index, value] of enumerate(arr))
    console.log(`index: ${index}, value: ${value}`);
// index: 0, value: a
// index: 1, value: b

폭로 나는 피토닉의 저자이자 관리자입니다.

~하듯이Kyle그리고.Shanoorsay is Array.prototype.entrys()

하지만 저 같은 초보자들에게는 그 의미를 완전히 이해하기 어렵습니다.

따라서 이해할 수 있는 예를 들어보겠습니다.

for(let curIndexValueList of someArray.entries()){
  console.log("curIndexValueList=", curIndexValueList)
  let curIndex = curIndexValueList[0]
  let curValue = curIndexValueList[1]
  console.log("curIndex=", curIndex, ", curValue=", curValue)
}

와 동등한python코드:

for curIndex, curValue in enumerate(someArray):
  print("curIndex=%s, curValue=%s" % (curIndex, curValue))
}

언급URL : https://stackoverflow.com/questions/34336960/what-is-the-es6-equivalent-of-python-enumerate-for-a-sequence

반응형