LoginSignup
11
6

More than 5 years have passed since last update.

ES6 の for-of 文でプロパティの値と一緒に index の値も取得する

Last updated at Posted at 2019-02-09

ES6 の for-of 文を使うとき, index の値も同時に取得したい状況が稀によくある.

これは Object.entries() の分割代入を行うことで実現できる:

const numArray = [0, 1, 2, 42]

for (const [index, num] of numArray.entries()) {
  console.log(`index: ${index}, num: ${num}`)
}

// index: 0, num: 0
// index: 1, num: 1
// index: 2, num: 2
// index: 3, num: 42

TypeScript の場合

TypeScript で targetES5 以下にしているとき, デフォルトでは上記のコードはコンパイルエラーとなる (TypeScript 3.2 で確認):

TS2569: Type 'IterableIterator<[number, number]>' is not an array type or a string type. Use compiler option '--downlevelIteration' to allow iterating of iterators.

エラーメッセージにあるように, --downlevelIteration オプションをつければコンパイルが通るようになる1:

tsconfig.json
{
    "compilerOptions": {
        "downlevelIteration": true,
        "target": "es5"
    }
}

参考にした記事

11
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
6