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

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

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をやろうとしていたので、せっかくなら今風の書き方を覚えておきたいところ。

コメント

このブログの人気の投稿

投稿時間:2021-06-17 05:05:34 RSSフィード2021-06-17 05:00 分まとめ(1274件)

投稿時間:2021-06-20 02:06:12 RSSフィード2021-06-20 02:00 分まとめ(3871件)

投稿時間:2024-02-12 22:08:06 RSSフィード2024-02-12 22:00分まとめ(7件)