2016-10-18 8 views
1

これは私の機能です。今は200 id.iがあるときにその吸う200 IDまで書くことを望んでいない。ここではforループを使用できますか?このここでは、100行のコードを書く代わりにforループを使用できますか?

for(i=0;i<200;i++){ 
    "areas": [ {"id": i}] 
} 

のようにこれはあなたのオブジェクトがある場合

var continentsDataProvider = { 
"map": "continentsLow", 

"areas": [ { 
    "id": 1, 
}, { 
    "id": "2", 
}, { 
}, { 
    "id": "3", 
}, { 
}, { 
    "id": "4", 
}, { 
}, { 
    "id": "5", 
}, { 
    } ] 

}; 
+0

200個のオブジェクトを含む配列が必要ですか? –

+0

はい、そうかもしれません。しかし、「領域」は好きではない:[{"" id ":i}]'。 'continentsDataProvider.areas.push({id:i});を使用します。' continentsDataProvider'は空の配列として 'areas'を含むオブジェクトです。 – Tushar

+0

@NinaScholzあなたのreply.yesに感謝します。私は配列が欲しいです。私は私の答えを得た。 – Mahi

答えて

5

はいあなたは、単にあなたのforループを実行します

var continentsDataProvider = { 
    "map": "continentsLow", 
    "areas": [] 
}; 

を試すことができ、私の関数でありますas

for(var i=1;i<=200;i++){ 
    continentsDataProvider.areas.push({"id": i}); 
} 
2

あなたはArray.from(非常に良く)オブジェクトを作成するために、またはあなたが使用できるforループを使用することができます。

var continentsDataProvider = { 
 
    "map": "continentsLow", 
 

 
    "areas": Array.from({ length: 200 }, function(k, v) { return { id: v + 1}; }) 
 
}; 
 

 
console.log(continentsDataProvider);

エミル・S.ヨルゲンセン中で述べたようにコメント - Array.fromはInternet Explorerではサポートされていませんので、ポリフィリングする必要があります(polyfill code)。

+1

IEを失うのを忘れないでください。https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/from#Browser_compatibility –

+0

確かに。私はそれを答えに加えます。 –

関連する問題