何が問題なのか分かりません。Node v5.6.0 NPM v3.10.6 コード: function (exports, require, module, __filename, __dirname) {
import express from 'express'
};
エラー: SyntaxError: Unexpected token import
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:140:18)
at node.js:1001:3
A friend of mine and I are currently discussing what is a closure in JS and what isn't. We just want to make sure we really understand it correctly. Let's take this example. We have a counting loop and want to print the counter variable on the console delayed. Therefore we use setTimeout and closures to capture the value of the counter variable to make sure that it will not print N times the value N. The wrong solution without closures or anything near to closures would be: for(var i = 0; i < 10; i++) {
setTimeout(function() {
console.log(i);
}, 1000);
}
which will of course print 10 times the value of i after the loop, namely 10. So his attempt was: for(var i = 0; i < 10; i++) {
(function(){
var i2 = i;
setTimeout(function(){
console.log(i2);
}, 1000)
})();
}
printing 0 to 9 as expected. I told him that he isn't using a closure to capture i, but he insists that he is. I proved that he doesn't use closures by putting the for loop body within another setTimeout (passing his anonymous function to setTimeout), printing 10 times 10 again. The same applies if I store his function in a var and execute it after the loop, also printing 10 times 10. So my argument is that he doesn't really capture the value of i, making his version not a closure. My attempt was: for(var i = 0; i < 10; i++) {
setTimeout((function(i2){
return function() {
console.log(i2);
}
})(i), 1000);
}
So I capture i (named i2 within the closure), but now I return another function and pass this around. In my case, the function passed to setTimeout really captures i. Now who is using closures and who isn't? Note that both solutions print 0 to 9 on the console delayed, so they solve the original problem, but we want to understand which of those two solutions uses closures to accomplish this.
Perl では、次の構文を使用して文字を複数回繰り返すことができます。 $a = "a" x 10; // results in "aaaaaaaaaa"
Javascript でこれを実現する簡単な方法はありますか? もちろん関数を使うこともできますが、組み込みのアプローチや他の巧妙なテクニックがあるかどうか知りたいです。
JavaScript で 2 つの文字列を使用して大文字と小文字を区別しない検索を実行しようとしています。 通常は次のようになります。 var string="Stackoverflow is the BEST";
var result= string.search(/best/i);
alert(result);
この/iフラグは大文字と小文字を区別しないことを意味します。 しかし、2 番目の文字列を検索する必要があります。フラグなしでも完璧に動作します。 var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(searchstring);
alert(result);
上記の例にフラグを追加すると、/i変数「searchstring」内の内容ではなく、searchstring が検索されます (次の例は機能しません)。 var string="Stackoverflow is the BEST";
var searchstring="best";
var result= string.search(/searchstring/i);
alert(result);
どうすればこれを実現できるでしょうか?