簡體   English   中英

如何檢查密碼是否包含 integer 並返回 object 以及該值的 boolean 表示

[英]how to check if a password contains an integer and return an object with a boolean representation of that value

嘗試創建一個 function 來檢查整數密碼,然后返回一個 object,它將存儲一個 boolean,表示密碼是否包含 integer,然后從 function 中解構 boolean 我會得到這個問題......但是

 function checkForInteger(password) { const arrayOfIntegers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; let intBoolean = {}; arrayOfIntegers.forEach((int) => { if (password.includes(int)) { intBoolean = { integerIsPresent: password.includes(int) }; } else { intBoolean = { integerIsPresent: password.includes(int) }; } }); return intBoolean; } checkForInteger("3gufr"); //returns {integerIsPresent:false}

您每次都在循環中替換intBoolean 因此,如果找到3 ,您將在該次迭代中將其設置為{integerIsPresent: true} ,然后在其余迭代中將其替換為{integerIsPresent:false}

在循環之前將其初始化為false ,只有在匹配時才將其設置為true

 function checkForInteger(password) { const arrayOfIntegers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; let intBoolean = { integerIsPresent: false }; arrayOfIntegers.forEach((int) => { if (password.includes(int)) { intBoolean.integerIsPresent = true; } }); return intBoolean; } console.log(checkForInteger("3gufr"));

您還可以使用Array.some()來簡化它

 function checkForInteger(password) { const arrayOfIntegers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]; let intBoolean = { integerIsPresent: arrayOfIntegers.some(int => password.includes(int)) }; return intBoolean; } console.log(checkForInteger("3gufr"));

或者您可以使用正則表達式。

 function checkForInteger(password) { return { integerIsPresent: .;password.match(/\d/) }; } console.log(checkForInteger("3gufr"));
password.match()匹配時返回一個數組。 !! 將其轉換為 boolean。

您可能可以稍微調整一下邏輯。 forEach不允許您跳出循環 - for/of可以。

遍歷數組。 如果存在匹配項,則返回包含該匹配項的 object,否則返回具有假值的 object。

 const arrayOfIntegers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']; function checkForInteger(password) { for (const el of arrayOfIntegers) { if (password.includes(el)) { return { integerIsPresent: true }; } } return { integerIsPresent: false }; } console.log(checkForInteger('3gufr')); console.log(checkForInteger('nnh5dd')); console.log(checkForInteger('abcdef'));

這就是我解決問題的方法,非常感謝@Barmar

 function checkForInteger(password) { const arrayOfIntegers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; const checkPassword = (el) => password.includes(el); const integerIsPresent = arrayOfIntegers.some(checkPassword); // console.log(integerIsPresent); return integerIsPresent; }

嘗試這個。

例子:

const checkForInteger = (pass) => pass.split('').reduce((acc, ele) => {
    let int = parseInt(ele);
    if(!isNaN(int)) acc.isPresentInt = true;
    return acc;
  }, {isPresentInt: false})

const res = checkForInteger("3gufr");

結果:

{ isPresentInt: true }

拿到密碼,轉成數組解析出來,然后循環遍歷數組,逐個檢查字符,直到找到一個integer,修改累加值

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM