let str = "i am writing an algorithm.";
//function to count alphabets
const alphabet_count = (str) => str.length;
//function to count words
const word_count = (str) => str.split(" ").length;
//function to count vowel
const vowel_count = (str) => (str.match(/[aeiou]/gi)).length;
//here i am trying to wrap all three functions in one
const sentence_read() = {alphabet_count(), word_count(), vowel_count()};
我正在嘗試將所有三個功能合二為一。
uj5u.com熱心網友回復:
const sentence_read = (str) => [alphabet_count(str), word_count(str), vowel_count(str)]
將回傳一個包含 3 個結果的陣列。用法 :
let str = "a word";
console.log(sentence_read(str)) // output : [6, 2, 2]
uj5u.com熱心網友回復:
您可以將它們包裝在這樣的物件中:
const counter = {
alphabet: alphabet_count,
word: word_count,
vowel: vowel_count,
}
然后在接受 2 個輸入的函式中使用這個物件;1. '計數單位' & 2. '字串'。
const count = (unit, str) => {
if(!counter[unit]) throw Error('Unit does not exist')
return counter[unit](str)
}
uj5u.com熱心網友回復:
使用模板字串
let str = "i am writing an algorithm.";
// function to count alphabets
const alphabet_count = (str) => str.length;
// function to count words
const word_count = (str) => str.split(" ").length;
//function to count vowel
const vowel_count = (str) => (str.match(/[aeiou]/gi)).length;
const sentence_read = (str) => `a_c : ${alphabet_count(str)}, w_c : ${word_count(str)}, v_c : ${vowel_count(str)}`
console.log(sentence_read(str)) // a_c : 26, w_c : 5, v_c : 8
如果要將物件中的函式分組,可以使用:
const str = "i am writing an algorithm.";
const counter = {
alphabet: (s) => s.length,
word: (s) => s.split(" ").length,
vowel: (s) => (s.match(/[aeiou]/gi)).length
}
const count = (unit, str) => {
if(!counter[unit]) throw Error('Unit does not exist')
return counter[unit](str)
}
console.log(count('alphabet', str)) // 26
console.log(count('word', str)) // 5
console.log(count('vowel', str)) // 8
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/398021.html
標籤:javascript 细绳 算法 功能
上一篇:使用printf時函式輸出錯誤
下一篇:如何在python中動態創建函式
