问题:
创建一个程序,提示输入数字列表,以空格分隔。让程序打印出仅包含偶数的新列表。
将输入转换为(数组)。许多语言都可以使用内置函数轻松地将字符串转换为数组,该函数可以根据指定的分隔符将字符串分开。
编写自己的算法-不要依赖该语言的内置过滤器或类似的枚举功能。
使用一个名为“ filterEvenNumbers”的函数来封装其逻辑。该函数接收旧数组并返回新数组。
我对此的所有注释:
//global array
var arr = [];
var arr = prompt("Enter your numbers");
// var eachNumber = arr.split(",");
var res = arr.split("");
console.log(arr);
console.log(res);
if(res = )
// var str = "How are you doing today?";
//push elements into array
// arr.push(prompt("Enter in a bunch of numbers", "")); //push input to array
// console.log(arr);
// https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array
// var arr = prompt("Enter your numbers").split(",");
// console.log(arr);
// var arr = [];
// for(var i = 0; i < 10; i++)
// arr.push(prompt("Enter a number");
// Convert number into array in Javascript
// https://stackoverflow.com/questions/20730360/convert-number-into-array-in-javascript
// var numbers = "1, 2, 3";
// var eachNumber = numbers.split(",");
// /* now parse them or whatso ever */
// console.log(eachNumber);
// JavaScript Array filter
// http://www.diveintojavascript.com/core-javascript-reference/the-array-object/array-filter
// The JavaScript Array filter method iterates over each value of an array passing it to a callback function.
// If the callback function returns true, the current value is then pushed into the resulting array.
// The callback function is invoked with three arguments: the value of the element, the index of...
// the element and the Array object being traversed.
// Bellow is an example of filtering odd and even numbers out of an array:
// var arr = [1, 2, 3, 4, 5];
// var odd = arr.filter(function(val) {
// return 0 != val % 2;
// });
// // odd = [1, 3, 5]
// var even = arr.filter(function(val) {
// return 0 == val % 2;
// });
// even = [2, 4]
// console.log(even);
// The Array filter method can also be used to remove empty, null or undefined elements from an array:
// var arr = [0, null, 42, undefined, "", true, false, NaN, "", "foo bar"];
// var filteredArr = arr.filter(function(val, num) {
// return !(val === "" || typeof val == "undefined" || val === null );
// });
// // // filteredArr = [0, 42, true, false, NaN, "foo bar"]
// console.log(filteredArr);
最佳答案
var a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
b = [];
for (var i = 0; i < a.length; ++i) {
if ((a[i] % 2) === 0) {
b.push(a[i]);
}
}
这是一个数组的示例,该数组查找偶数并将其推入另一个数组。您可以轻松更改它,它不会将其推入另一个数组,而是打印偶数。它将帮助您解决问题
关于javascript - 只打印偶数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45928757/