我想创建一个需要数字的javaScript程序。如果数字包含偶数,则数字将显示为没有偶数
请原谅代码,看起来似乎很蠢,我还在尝试理解javascript ..
我已尝试过这个
<script type="text/javascript">
var userInput = prompt("choose an even number");
var evenNumbers = [2,6,4,8,10];
for ( x=0; x<evenNumbers.length; x++) {
userInput -= evenNumbers[x];
document.write( userInput );
}
</script>
答案 0 :(得分:0)
您可以使用Array#filter
排除值数组中的特定值。
// var userInput = prompt("choose an even number");
var userInput = '3456789'
function excludeEvenNumber(x) {
return x.split('') // split the numbers on each character
.filter(function(y) { return Number(y) % 2 !== 0 }) // filter out even numbers
.join('') // join the character array into a string
}
console.log(
excludeEvenNumber(userInput)
)
答案 1 :(得分:0)
<script type="text/javascript">
<!--
var userInput = prompt("Please provide an even number!","");
if(userInput%2 ==0){
document.write('<span style="color:green">That`s correct!</span>');
}else{
document.write('<span style="color:blue">'+userInput+'</spam=n><span style="color:red"> isn`t a even number!');
}
//-->
</script>
&#13;
答案 2 :(得分:0)
我不确切地知道你想要达到的目标,但我赞成两个可能的预期结果:
首先:
如果用户介绍,则可以使用以下数字: 123456
您希望显示相同的字符串,而不使用偶数,例如: 135
如果这是正确的,我的答案是:
var userResult = new Array();
var userInput = prompt("choose an even number");
//Split the string to have every number independent
var number = userInput.split("");
//For every number
for (var x=0; x<number.length; x++) {
//Check if it's a odd number (so it's not a even number)
if( (number[x] % 2) != 0){
//Push the number to the result
userResult.push(number[x]);
}
}
//Re-format the result to have it as a string without commas
document.write(userResult.join(""));
第二
如果用户介绍,则可以使用以下数字: 4
你想要显示你的数字数组而不是数字(如果是偶数): 2,6,8,10
如果这是正确的,我的答案是:
var userInput = prompt("choose an even number");
var evenNumbers = [2, 6, 4, 8, 10];
//Check if it's a even number
if( (userInput % 2) == 0){
//If it is, find where is this number on your evenNumbers array...
for (var x=0; x<evenNumbers.length; x++) {
//..and remove it from the array
if(userInput == evenNumbers[x]){
evenNumbers.splice(x, 1);
break;
}
}
}
document.write(evenNumbers);