文字列を関数に渡して配列にプッシュするコードを単純化しようとしています。ここで私は前に持っていたし、それが働いたものです:foreachループで関数を定義できません
var hi = [];
function hello(input) {
console.log(input);
hi.push(input);
}
var bye = [];
function goodbye(input) {
console.log(input);
bye.push(input);
}
<button onclick="hello('example');">Should print example in console log</button>
<button onclick="goodbye('example2');">Should print example2 in console log</button>
私は、このように、その中の各機能を持つ配列を持っているために、これを変更:
var options = [
["hello", "hi"],
["goodbye", "bye"]
];
options.forEach(function(option) {
var arr1 = option[0]; // should be hello or goodbye
var arr2 = option[1]; // should be hi or bye
function arr1(input) {
console.log(input);
arr2.push(input);
}
});
<button onclick="hello('example');">
Should print example in console log
</button>
<button onclick="goodbye('example2');">
Should print example2 in console log
</button>
しかし、ここでボタンの1つをクリックすると、次のいずれかが表示されます。関数hello
またはgoodbye
は定義されていません。
JsFiddle:https://jsfiddle.net/gaorxnto/
だけで作成することはありません、ループ内で関数を呼び出しますループ内の関数です。 – antfuentes87
まず、 'hello()'や 'goodbye()'ではなく 'arr1()'という関数を作成します。 'Global [arr1] = function(){}'を実行する必要がありますあなたも[scope](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/let)の問題を修正しました)。しかし、@ antfuentes87のように、それは良い解決策ではありません – Arthur
ここでhelloとgoodbye関数の定義はありますか? –