LoginSignup
0
0

More than 5 years have passed since last update.

AtCoderでアロー関数を利用したときは'use strict'を利用する

Last updated at Posted at 2019-01-18

A - はじめてのあっとこーだー(Welcome to AtCoder)で早速詰まったのでメモ。

失敗したコード

let sum = array => {
  return parseInt(array[0]) + parseInt(array[1]);
};

function Main(input) {
  input = input.split('\n');
  const tmp = input[1].split(' ');
  const a = +input[0];
  const b = sum(tmp);
  const s = input[2];
  //出力
  console.log(`${a + b} ${s}`);
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));

ある処理をアロー関数にまとめて、テスト実行したところ次のようなエラーになった。

/imojudge/Main.js:2
let sum = array => {
^^^

SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode
    at exports.runInThisContext (vm.js:53:16)
    at Module._compile (module.js:387:25)
    at Object.Module._extensions..js (module.js:422:10)
    at Module.load (module.js:357:32)
    at Function.Module._load (module.js:314:12)
    at Function.Module.runMain (module.js:447:10)
    at startup (node.js:148:18)
    at node.js:405:3

【node.js】npmで SyntaxError: Block-scoped declarations (let, const, function, class) not yet supported outside strict mode というエラーで怒られるを参考にしたところ、

githubのissueにあがってました

Version 0.7.0 of source-map fails to load on Node < 6 due to let without 'use strict'. This causes the following error:

https://github.com/gulp-sourcemaps/gulp-sourcemaps/issues/343

node moduleのsource-map 0.7.0は
'use strict'を使用しないのでnodeのversion<6(6未満)にはロードできないらしい。
そのせいでエラーが発生するとのこと。

なのでソースの先頭に'use strict'をつけてから実行したところ、成功した。

成功したコード

'use strict'
let sum = array => {
  return parseInt(array[0]) + parseInt(array[1]);
};

function Main(input) {
  input = input.split('\n');
  const tmp = input[1].split(' ');
  const a = +input[0];
  const b = sum(tmp);
  const s = input[2];
  //出力
  console.log(`${a + b} ${s}`);
}
Main(require('fs').readFileSync('/dev/stdin', 'utf8'));

ES2015の学習がてらAtCoderをやろうとしていたので、せっかくなら今風の書き方を覚えておきたいところ。

0
0
3

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
0
0