【问题标题】:wrap a function in javascript在javascript中包装一个函数
【发布时间】:2021-12-26 13:08:53
【问题描述】:
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()};

我正在尝试将所有三个功能合二为一。

【问题讨论】:

    标签: javascript string algorithm function


    【解决方案1】:
    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]
    

    【讨论】:

    • 这行得通,谢谢...
    【解决方案2】:

    使用模板字符串

    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

    【讨论】:

      猜你喜欢
      • 2021-07-10
      • 2013-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 2010-09-24
      相关资源
      最近更新 更多