我開發了一個函式來計算給定陣列中“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);
uj5u.com熱心網友回復:
對于您的資料
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]
CodeSandbox:https ://codesandbox.io/s/lucid-keldysh-9meo3j?file=/src/index.js:38-186
uj5u.com熱心網友回復:
我已經更新了函式來計算"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));
uj5u.com熱心網友回復:
將給定的數字陣列轉換為單個字串的陣列:
/**
* @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));
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/463142.html
標籤:javascript 数组
