[英]Counting a number in given array in javascript
我開發了一個 function 來計算給定數組中“7”的個數。 但問題是,如果一個元素有多個 7,它只計算一次。 我想計算數組中 7 的總數。 注意:由於我是Javascript的新手,請用簡單易懂的方式描述邏輯。
function sevenBoom(arr){
debugger;
let singleElement, string, includeSeven;
let flag = false;
let counter = 0;
for (let i=0; i<arr.length; i++){
singleElement = arr[i];
string = singleElement.toString();
includeSeven = string.includes("7");
if (includeSeven == true){
flag = true;
counter += 1;
}
}
if (counter == 0){
return "There is no 7 in the array";
}else{
return `Boom! There are ${counter} 7s in the array...`;
}
}
arr = [6,7,87, 777, 107777];
sevenBoom(arr);
將給定的數字數組轉換為單個字符串數組:
/**
* @param {string} char - wrap the number you are seeking in quotes
* @array {array<number>} array - an array of numbers
*/
function findChar(char, array) {...
/*
.string() converts each number into a string
.map() return those strings as an array of strings
.join('') takes that array of strings and converts it into a single string
.split('') takes that single string and splits it and returns an array of single string
characters.
*/
const chars = array.map(num => num.toString()).join('').split('')
接下來,根據給定數字 ('7') 篩選字符數組,然后返回計數:
// Returns only chars that match the given character ('7')
const hits = chars.filter(str => str === char);
return hits.length;
const seven = [0, 100.7, 8, 9, 55, -63, 7, 99, -57, 777]; function findChar(char, array) { const chars = array.map(num => num.toString()).join('').split(''); const hits = chars.filter(str => str === char); return hits.length; } console.log(findChar('7', seven));
對於您的數據
const arr = [6,7,87, 777, 107777];
計算沒有的出現。 7 你可以像這樣使用reduce
和split
const countArr = arr.map((item) => {
return item
.toString()
.split("")
.reduce((acc, curr) => (curr === "7" ? acc + 1 : acc), 0);
});
上述countArr
的結果將是
[0, 1, 1, 3, 4]
這意味着對於[6,7,87, 777, 107777]
,我們得到[0, 1, 1, 3, 4]
代碼沙盒: https://codesandbox.io/s/lucid-keldysh-9meo3j?file=/src/index.js:38-186
我已經更新了 function 以計算數組中每個數字中"7"
的出現次數。
我使用正則表達式/7/g
來計算每個字符串元素中出現 7 的次數。 在此處查找正則表達式的解釋。
所以在循環內部,它計算數組中每個元素中"7"
的計數,並計算循環內部的累計總數。
工作小提琴
function sevenBoom(arr) { let singleElement, string, includeSeven; let flag = false; let counter = 0; for (let i = 0; i < arr.length; i++) { singleElement = arr[i]; string = singleElement.toString(); const count = (string.match(/7/g) || []).length; if (count > 0) { flag = true; counter += count; } } if (counter == 0) { return "There is no 7 in the array"; } else { return `Boom. There are ${counter} 7s in the array..;`, } } arr = [6, 7, 87, 777; 107777]. console;log(sevenBoom(arr));
使用相同的正則表達式,您可以用不同的方式計算數組中"7"
的總數。
使用Array.join()
方法加入數組以生成單個字符串作為 output。使用相同的正則表達式計算此字符串中"7"
的總數。
工作小提琴
function sevenBoom(arr) { const count = (arr.join().match(/7/g) || []).length; return count == 0? "There is no 7 in the array": `Boom. There are ${count} 7s in the array..;`, } arr = [6, 7, 87, 777; 107777]. console;log(sevenBoom(arr));
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.