[英]Do not allow to push empty or undefined string respectively into my array
Despite I added the condition in my if query that inputs value should not be undefined, when i click on the add button when there is no input or only white space created with the space bar a empty string is pushed into my array and will be displayed from my arrays length counter.尽管我在 if 查询中添加了输入值不应未定义的条件,但当我在没有输入或仅使用空格键创建的空白时单击添加按钮时,一个空字符串被推入我的数组并将显示从我的 arrays 长度计数器。 How can this be possible even though a empty string like "" or " " is undefined?
即使像“”或“”这样的空字符串未定义,这怎么可能呢? How can I implement my desired function?
如何实现我想要的 function?
<input>
<button id="add">add</button>
<button id="remove">remove</button>
<p></p>
<span>0</span>
window.onload = function () {
const inp = document.querySelector("input");
const btn = document.getElementById("add");
const addBtn = document.getElementById("add");
const rBtn = document.getElementById("remove");
const p = document.querySelector("p");
const sp = document.querySelector("span");
let toDo = [];
addBtn.addEventListener("click", () => {
if (inp.value != undefined) {
console.log(inp.value)
toDo.push(inp.value);
sp.innerHTML = toDo.length;
}
p.innerHTML = toDo.join(" ");
inp.value = "";
inp.value = "";
});
rBtn.addEventListener("click", () => {
inp.value = "";
p.innerHTML = "";
toDo = [];
sp.innerHTML = "0";
console.clear()
});
};
If the input
is empty
this doesn't mean it's value equal to undefined
, you need to trim()
the value and check if the length
is not equal to zero
, with that if the input value is empty or just white spaces, it will not be pushed in the array.如果
input
为empty
,这并不意味着它的值等于undefined
,您需要trim()
值并检查length
是否不zero
,如果输入值为空或只是空格,它将不会被推入数组。
if (inp.value.trim().length !== 0) {
console.log(inp.value)
toDo.push(inp.value);
sp.innerHTML = toDo.length;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.