![](/img/trans.png)
[英]I need to loop through an array and find the people that are under age 18 . Should i convert it to String (toString) first?
[英]How could I convert many randomly generated integers into a string of an array in order to perform the forEach() method to check if age >= 18 [DESC]
我正在嘗試一種不尋常的方法,將隨機生成的整數轉換為字符串,然后使用 split() 方法將字符串轉換為包含生成數字的數組列表,這樣我就可以對內部的每個元素執行 function使用 forEach() 方法的數組。
我的目標是 forEach() 方法檢查數組內是否所有隨機生成的整數都大於或等於 18,否則返回 'lower than 18', age
到目前為止,這就是我所帶來的,但我被困住了:
<p id="demo"></p>
<button onclick="myFunction()">Try</button>
var numbers1 = Math.floor(Math.random() * 25 + 1).toString()
var numArr = numbers1.split(",").map(createAnArray)
function createAnArray(item) {
return parseInt(item)
}
console.log(numArr)
function myFunc(age) {
if (age >= 18) {
return "age suceeds", age >= 18;
}
else if (age != 18 || age === 17) {
document.getElementById('demo').innerHTML = 'lower than 18', age;
} else {
return 'flop'
}
}
function myFunction() {
document.getElementById("demo").innerHTML = numArr.find(myFunc);
}
我想你可能想要這樣的東西
function randomNumbers(maximum, minimum, arrlen) { return Array.from( // create an array { length: arrlen }, // give it an optional length () => (Math.floor(Math.random() * (maximum - minimum + 1)) + minimum) // generate random numbers in a range ); } console.log(randomNumbers(30, 15, 10));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.