2017-12-30 5 views
0

文字列を関数に渡して配列にプッシュするコードを単純化しようとしています。ここで私は前に持っていたし、それが働いたものです: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/

+2

だけで作成することはありません、ループ内で関数を呼び出しますループ内の関数です。 – antfuentes87

+0

まず、 'hello()'や 'goodbye()'ではなく 'arr1()'という関数を作成します。 'Global [arr1] = function(){}'を実行する必要がありますあなたも[scope](https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Instructions/let)の問題を修正しました)。しかし、@ antfuentes87のように、それは良い解決策ではありません – Arthur

+0

ここでhelloとgoodbye関数の定義はありますか? –

答えて

1

まずアクセスできるようにarr1値になりませんarr1 = function() {}をやって、窓に取り付けますが、arr1という関数を作成します。 ------を

var options = [ 
    ["hello", "hi"], 
    ["goodbye", "bye"] 
]; 
options.forEach(function(option) { 
    window[option[1]] = [] // Init array 
    window[option[0]] = function(val) { // Create event 
    window[option[1]].push(val) 
    console.log(val + " added to " + option[1]) 
    } 
}); 

----- UPDATE:

あなたは、ほとんどのグローバルスコープ(クライアント側の窓)

let arr1 = 'hello' 
window[arr1] = function() {} 

テストされていないソリューションを使用する必要があります

このような新しいグローバル変数/ scropeを作成することは、本当に良い解決策ではありません。追加するものは何ですか?

var options = [ 
    ["var", "return"], 
    ["function", "default"] 
]; 

すべてのjavascriptの予約キーワードですreturndefaultと2機能var()function()と呼ばれる2つの配列を作成しようとするでしょう。

var()またはreturn.push()エラーを作成し、あなたがwindow.var()またはwindow.return.push()(またはvar option = 'var'; window[option]();)を使用するように強制されます

別の解決策

// Store all your inputs on a single variable, ex: results.hi = [1,2,3] 
let results={}; 

// A single function to call. ex: addTo(`hello`, 1) 
function addTo(category, val) { 
    // Find the accosiate option 
    let option = options.find(opt=> { return opt[0] === category }) 
    // First time, init the array 
    if(!results[category]) { 
    results[category] = [] 
    } 
    // Push new value 
    results[category].push(val) 
} 
+0

ありがとうアーサー、私はこれを試してみます。しかし、ループの中で関数を呼び出すことについてantfuentes87が言ったことに興味がありました。これにリンクがありますか? –

+0

いいえ、私は別の解決策だと思います:単一の関数を作成し、毎回カテゴリを渡すことで呼び出します: 'let results = {}; function addTo(category、val){letオプション= options.find(opt => {return opt [0] === category}); if(!results [category]){results [category] ​​= []}結果[カテゴリ] .push(val); } '(テストなし) – Arthur

+0

ありがとう、私はそれを理解しているので、私はあなたの最初の解決策に固執すると思います。再度、感謝します! –

1

あなたがそれを達する傾けるようあなたは、ループ内で関数を作成します。 DOMは、私がコメントで言うように、それは

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 
 
    window[arr1] = function(input) { 
 
    console.log(input); 
 
    } 
 
});

https://jsfiddle.net/gaorxnto/2/ 
関連する問題