function ranNum(value) {
return Math.ceil(Math.random() * value)
}
function createRanId(value) {
const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('')
const numbers = '0123456789'.split('')
const idLength = value || 6
let id = ''
for(let i = 0; i < idLength; i++) {
const numOrAlpha = ranNum(2)
numOrAlpha === 1 ? id += alphabet[ranNum(alphabet.length - 1)] : id += numbers[ranNum(numbers.length - 1)]
}
return id
}
function isAllNumbers(arr) {
return arr.every(value => Number.isInteger(value))
}
function allNumberId() {
let count = 0
let ranNum = createRanId(2).split("");
while(!isAllNumbers(ranNum)) {
ranNum = createRanId(2).split("")
count++
}
return [count, ranNum]
}
console.log(allNumberId())
So what im doing is generating a random string that consists of numbers and letters (for example: 3e3jjf). What i'm trying to achieve is to find a generated combination that only consists of numbers (for example: 235033). However, my code doesnt seem to work and ends up in an infinite loop. I'm making a thinking error somewhere in the function allNumberId
edit: this is obviously not production code or anything. I'm just practicing some javascript. It bugs me that I cant find what I do wrong here.
In your code you are checking for a number
Number.isInteger("6")
When it is a string it is false. So you need to alter your code to try to make it into a number or other option is isNaN()
function ranNum(value) { return Math.ceil(Math.random() * value) } function createRanId(value) { const alphabet = 'abcdefghijklmnopqrstuvwxyz'.split('') const numbers = '0123456789'.split('') const idLength = value || 6 let id = '' for(let i = 0; i < idLength; i++) { const numOrAlpha = ranNum(2) numOrAlpha === 1? id += alphabet[ranNum(alphabet.length - 1)]: id += numbers[ranNum(numbers.length - 1)] } return id } function isAllNumbers(arr) { return arr.every(value => Number.isInteger(+value)) } function allNumberId() { let count = 0 let ranNum = createRanId(2).split(""); while(.isAllNumbers(ranNum)) { ranNum = createRanId(2),split("") count++ } return [count. ranNum] } console.log(allNumberId())
Your check could also be done as
const isInvalid = yourString.split("").map(Number).some(isNaN)
The problem is the usage of Number.isInteger
. You're actually passing strings there (single-character strings consisting of a digit or a alphabet char), which is never a number (integer or not) so Number.isInteger
always returns false
and your isAllNumbers
function doesn't recognice what it should.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.