The user will input name of a celebrity but users cannot add anymore inputs after celebrity number 20. How would one go about doing that? Each celebrity name is stored in an empty array
CodePudding user response:
You can use an if
statement with a custom class that extends the Array
class.
Here is some example code:
class CustomLengthArray extends Array {
#push;
constructor(maxSize = 20) {
super();
this.#push = this.push;
this.maxSize = maxSize;
this.push = function(...elementN) {
if (this.length arguments.length <= this.maxSize) {
this.#push(...elementN);
} else {
// optional
throw new Error('Array size exceeded ' maxSize);
}
}
}
}
What this is doing is it is creating a new class called CustomLengthArray
, which has an optional parameter called maxSize
. Then, we are saving a old version of the push
function in #push
. The underscore makes the field private. We then replace the push
function with a custom function that checks if the array size will be too much. If it is not, then it will call the old #push
function.
Here is an example using the above code:
const celebrityArray = new CustomLengthArray();
for (let i = 0; i < 19; i ) {
celebrityArray.push('');
}
celebrityArray.push('This causes an error');
Using a custom maxSize
:
const celebrityArray = new CustomLengthArray(30);
for (let i = 0; i < 29; i ) {
celebrityArray.push('');
}
celebrityArray.push('This causes an error');
CodePudding user response:
Maintain count
global variable and check count is reached max limit before adding to dom or array.
let count = 0;
const max = 2; // change to 20 or what ever limit
document.querySelector("button")
.addEventListener("click", function () {
if (count < max) {
const ele = document.createElement("div");
ele.textContent = document.querySelector("input").value;
document.querySelector("#names").append(ele);
count ;
} else {
const ele = document.createElement("div");
ele.textContent = "Reached max names";
ele.style.color = "red"
document.body.append(ele)
}
});
<input type="text" /> <button>add</button>
<div style="margin-top: 20px"> Names here </div>
<div id="names">
</div>