हमारे पास एक सरणी है जिसमें कुछ खाली मान हैं:
const arr = [43, 534534, 645, 64, , 645, 64, , 645, , 645, , 65, , 645, , 64];
हमें एक सरणी फ़ंक्शन pushAtEmpty() लिखना है जो एक तत्व लेता है और उसे सरणी में मिलने वाले पहले खाली सूचकांक पर डालता है जिसके संदर्भ में इसका उपयोग किया जाता है। यदि कोई खाली स्थान नहीं है, तो तत्व को सरणी के अंत में डाला जाना चाहिए।
आइए इस फ़ंक्शन के लिए कोड लिखते हैं। हम पहले खाली स्थान का सूचकांक खोजेंगे और फिर वहाँ के मान को दिए गए मान से बदल देंगे।
उदाहरण
const arr = [43, 534534, 645, 64, , 645, 64, , 645, , 645, , 65, , 645, , 64];
Array.prototype.pushAtEmpty = function(element) {
let index;
for (index = 0; index < this.length; index++) {
if (arr[index] === undefined) {
this.splice(index, 1, element);
break;
}
}
if (index === this.length) {
this.push(element);
}
};
arr.pushAtEmpty(23);
arr.pushAtEmpty(33);
arr.pushAtEmpty(43);
arr.pushAtEmpty(53);
arr.pushAtEmpty(63);
arr.pushAtEmpty(73);
arr.pushAtEmpty(83);
arr.pushAtEmpty(93);
console.log(arr);
आउटपुट
कंसोल में आउटपुट होगा:
[ 43, 534534, 645, 64, 23, 645, 64, 33, 645, 43, 645, 53, 65, 63, 645, 73, 64, 83, 93 ]