【问题标题】:Take word from list, run function, and move on to next word从列表中取出单词,运行函数,然后继续下一个单词
【发布时间】:2019-06-16 11:54:45
【问题描述】:

我有一个文本文件(每个单词之间用', ' 分隔)和一个函数,它在运行时为单词分配一个值(其中a = 1、z = 26)。 (例如:sumChars('JavaScript') 返回119。)我的问题是,我如何只获取第一个单词,然后运行该函数,然后继续下一个单词?我知道使用fetch(url) 获取文件后,我可以使用.then(d => d.replace(/\n/, '')).then(d => d.replace("', '", '')) 摆脱其他所有内容。

【问题讨论】:

  • 尝试将您的字符串拆分为一个数组,然后将您的函数调用到每个元素:const resp = d.split(', ').map(x => sumChars(x))

标签: javascript


【解决方案1】:

在Javascript中处理字符串最好的方法是使用正则表达式,加上g(全局)标志来处理字符串中的所有出现。

var list = [], sums = [];

fetch(url) 
 .then(txt => list = txt.replace(/\n/g, '').replace(/\s/g, '').split(","); return list;)
 .then(res => res.forEach((wrd,idx,arr) => { sums[idx]=0; 
 wrd.split('').forEach(char => sums[idx] += char.charCodeAt(0)-96)}) 
    );

console.log("result: ", list,sums);

作为获取字符值convert characters to ascii code的参考。
作为在 foreach 循环中绑定数组元素的参考foreach loop by reference。

【讨论】:

    猜你喜欢
    • 2020-06-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-26
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多