是否有一种方法来返回字符出现在字符串数组不使用任何内置函数?



我有麻烦与我的功能,我需要找到多少次字符出现在数组内的字符串。我们不允许使用任何内置函数,因此array.toString()是不可能的。到目前为止,这是我想出的代码:

function occur(arr){
let strings = "";
let result1 = "";
let output = "";
let display = "";
let counter = 0;

// Convert array to string
for (let i = 0; i < arr.length; i++){
strings = arr[i];
display += arr[i] + (i < arr.length - 1? "-": "");

// Convert string to letters
for (let j = 0; j < strings.length; j++){
result1 = strings[j];
// Scans letters for match
for (let x = 0; x < result1.length; x++){
if (result1 === "o"){
counter++;
output +=counter + (j > arr.length? "-": "");
}
}
}
}
console.log(display);
console.log(counter);
console.log(output);
}
occur(["Sophomore", "Alcohol", "Conquer", "RockyRoad"]);

,输出应该像这样:

  • Sophomore-Alcohol-Conquer-RockyRoad(数组)
  • 8(字母出现次数)
  • 3 -2 - 1 -2(每个字符串中的字母数)

我必须将数组转换为字符串,并扫描每个字符串中出现的字母。任何关于第三输出的帮助将是非常感激的!

您应该利用语言。语言提供了许多我们不应该自己编写的函数。

用于例如:你可以在数组上使用join函数来连接字符串。

你还应该使用高阶函数,比如map和reduce,而不是for循环。

最后一件事尝试推广解决方案。所以你可以在函数中传递字符,而不是寻找'o'。这是我的解决方案

const counter = (arr,char) =>{
const result1 = arr.join('-');
const count = arr.map((str) =>{
const total_occurance = str.split('').reduce((count,character) => {
if(character === char){
return count+1;
}
return count;
},0);
return total_occurance;
});
const result2 = count.reduce((totalCount,value) => totalCount+value,0);
const result3 = count.join('-');
console.log({result1,result2,result3});
}
counter(["Sophomore", "Alcohol", "Conquer", "RockyRoad"],'o');

,因为不允许使用内置函数。你可以用这个

function occur(arr){
let strings = "";
let result1 = "";
let output = "";
let display = "";
let total_count=0; 
// Convert array to string
for (let i = 0; i < arr.length; i++){
strings = arr[i];
display += arr[i] + (i < arr.length - 1? "-": "");
let counter = 0;
// Convert string to letters
for (let j = 0; j < strings.length; j++){
result1 = strings[j];
// Scans letters for match

if (result1 === "o"){
counter++;
total_count++;
}

}
output +=counter + (i < arr.length-1? "-": "");
}
console.log(display);
console.log(total_count);
console.log(output);
}
occur(["Sophomore", "Alcohol", "Conquer", "RockyRoad"])

您可以通过数组映射并使用reduce计数字符o出现的总次数。最后,用join将带有-符号的字符串粘接。

const arr = ["Sophomore", "Alcohol", "Conquer", "RockyRoad"];
const counts = arr.map(
item => item.split('')
.reduce((count, char) => {
return char === 'o' ? ++count : count;
}, 0)
);
console.log('Output: ', arr.join('-'));
console.log('Total: ', counts.reduce((acc, curr) => acc + curr));
console.log('Each String: ', counts.join('-'));
.as-console-wrapper{min-height: 100%!important; top: 0}

let arr = ["Sophomore", "Alcohol", "Conquer", "RockyRoad"];
let counter = 0;
let display = arr.join("-");
let result = arr.map(x => {
let count = x.match(/o/ig)?.length;
counter += count;
return count;
})
console.log(display);
console.log(counter);
console.log(result.join("-"));