यह उत्तर Array.forEach
किसी भी पुस्तकालय के बिना, केवल देशी वेनिला पर आधारित है ।
मूल रूप से something()
3 बार कॉल करने के लिए , उपयोग करें:
[1,2,3].forEach(function(i) {
something();
});
निम्नलिखित कार्य पर विचार:
function something(){ console.log('something') }
चौकी होगी
something
something
something
इस प्रश्न को पूरा करने के लिए, something()
क्रमशः 1, 2 और 3 बार कॉल करने का एक तरीका है :
यह 2017 है, आप ES6 का उपयोग कर सकते हैं:
[1,2,3].forEach(i => Array(i).fill(i).forEach(_ => {
something()
}))
या अच्छे पुराने ES5 में:
[1,2,3].forEach(function(i) {
Array(i).fill(i).forEach(function() {
something()
})
}))
दोनों ही मामलों में, चौकी होगी
चौकी होगी
something
something
something
something
something
something
(एक बार, फिर दो बार, फिर 3 बार)