[英]print out only even numbers
問題:創建一個程序以提示輸入數字列表,並用空格分隔。 讓程序打印出僅包含偶數的新列表。
將輸入轉換為(數組)。 許多語言都可以使用內置函數輕松地將字符串轉換為數組,該函數可以根據指定的分隔符將字符串分開。 編寫自己的算法-不要依賴該語言的內置過濾器或類似的枚舉功能。 使用一個名為“ 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]);
}
}
這是一個數組的示例,該數組查找偶數並將其推入另一個數組。 您可以輕松更改它,它不會將其推入另一個數組,而是打印偶數。 它將幫助您解決問題
您是否有部分問題您不理解? 你有什么問題嗎?
為了提示用戶輸入,您可以使用window.prompt('Enter a list of numbers separated by spaces');
這種接收用戶輸入的方式將返回一個字符串。 由於不允許使用內置方法將其轉換為列表,因此可以采取的一種方法是:
currentInteger
來保存您正在字符串中查看的當前數字的數字(請記住:數字可以長於單個數字,因此在字符串中進行迭代時,當前數字可能不會由您所用的單個字符表示在看) currentInteger
已完成,如果它是偶數整數,則將其追加到新列表中。 由於您的currentInteger變量是一個字符串,因此您將需要使用parseInt()將其設為數字並檢查其是否為偶數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.