[英]How to show a zero before the all 0-9 numbers that input in the textbox?
[英]Is input contains all numbers from 0-9 JS
嘿,伙計們,我正在為這個練習而苦苦掙扎。 我試圖檢查輸入是否包含 0-9 的所有數字。 例如,如果輸入是“0a1b2345asd6s7e89”它應該返回真,“123789”它應該是假的。 我嘗試了下面的代碼,但我覺得我正朝着錯誤的方向前進。 也許正則表達式? 請幫忙。
const test = (input) => { const arrayOfNumbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] const inputArray = [...input] inputArray.every(el => { arrayOfNumbers.forEach(elNumber => { elNumber === el }) }) }
const test = (a, b) => a.every(el => b.includes(el) ? true : false)
然后你可以像這樣使用它
const ax = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
var ab = "0a1b2345asd6s7e8"
test(ax,ab)
// -> false
ab = "0a1b2345asd6s7e89"
test(ax,ab)
// -> true
嘗試every
, includes
:
const test = input => [...Array(10).keys()].every(digit => input.includes(digit)); console.log("Expected output - true:", test("0a1b2345asd6s7e89")); console.log("Expected output - false:", test("123789"));
[...Array(10).keys()]
是一個 0 到 9 的數組。對.every()
的回調確保輸入包含每個數字至少一次。
在這個解決方案中,我使用了include()
和indexOf()
包括:驗證測試(輸入字符串)是否包含 0-9 的數字
indexoOf:驗證數字是否從 0-9(升序)
解決方案:
function Test(){
let ContAllNumber = 0; //0 = false, 1 = true
var test = "0a1b2345asd6s7e89";
const arrayNum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for(let i = 0; i < test.length; i++){
if(test.includes(i)){
arrayNum[i] = test.indexOf(i);
}
else{
break;
}
}
for(let i = 0; i < 9; i++){
if(arrayNum[i] < arrayNum[i+1]){
ContAllNumber = 1;
}
else{
ContAllNumber = 0;
break;
}
}
console.log(ContAllNumber);
//condition : contains number from 0 - 9
//example respecting condition: 0123456789, 0a1b2345asd6s7e89
//example NOT respecting condition: 7193456082 , a0s93as0j4
}
調試:
(我建議您嘗試它以更好地理解代碼)
function Test(){
let ContAllNumber = 0; //0 = false, 1 = true
var test = "0123456789";
const arrayNum = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
for(let i = 0; i < test.length; i++)
{
if(test.includes(i))
{
arrayNum[i] = test.indexOf(i);
console.log("number: " + i);
console.log("position: " + arrayNum[i]);
}
}
for(let i = 0; i < 9; i++)
{
if(arrayNum[i] < arrayNum[i+1])
{
ContAllNumber = 1;
console.log("position of number " + i + " is " + arrayNum[i] + " and position of the next number " + (i + 1) + " is " + arrayNum[i+1] + "so it's respecting condition (ok)");
console.log("so you can return 1 (true)");
}
else
{
ContAllNumber = 0;
console.log("position of number " + i + " is " + arrayNum[i] + " and position of the next number " + (i + 1) + " is " + arrayNum[i+1] + "it is NOT respecting condition (NOT OK)");
console.log("so you can return 0 (false)");
break;
}
}
console.log(ContAllNumber);
//condition = contains number from 0 - 9
//example respecting condition: 0123456789, 0a1b2345asd6s7e89
//example NOT respecting condition: 7193456082 , a0s93as0j4
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.