如何解决如何使用javascript中先前函数的输出调用函数
停留在 JavaScript 中的这一小部分。我目前有一个程序,当按下按钮时,它会接收一个输入文件并逐行读取它并确定哪些行是回文,然后将它们输出到控制台。我的目标是获取这些回文并在它们上运行下一个函数(称为频率)并将函数的结果输出到控制台。但是,我不知道该怎么做。
这是我的代码:
window.addEventListener('load',function() {
document.getElementById("myBtn").addEventListener("click",function() {
var reader = new FileReader();
reader.addEventListener('load',function() {
const sentences = this.result.split(/\r?\n/);
const palindromes = sentences.filter((line) => {
return palindrome(line);
});
console.log('all sentences:',sentences);
console.log('only palindromes:',palindromes);
});
reader.readAsText(document.querySelector('input').files[0]);
});
},true);
function palindrome(str) {
if (str === '')
return false;
var re = /[\W_]/g;
var lowRegStr = str.toLowerCase().replace(re,'');
var reverseStr = lowRegStr.split('').reverse().join('');
return reverseStr === lowRegStr;
}
function frequency(str) {
//some code
}
<label for="upload">Upload file to find palindromes:</label>
<br />
<input type="file" name="upload" id="upload">
<button id="myBtn">Go!</button>
有什么建议吗?谢谢!
编辑:这是我输入的内容
mom
Racecar!
another line
解决方法
你需要在回文上运行它
const re = /[\W_]/g;
const clean = word => word.replace(re,'');
const palindrome = str => {
if (str === '') return false;
var lowRegStr = clean(str).toLowerCase(); // compare clean
var reverseStr = lowRegStr.split('').reverse().join('');
console.log(lowRegStr,reverseStr)
return reverseStr === lowRegStr;
};
const frequency = s => [...s].reduce((a,c) => (a[c] = a[c] + 1 || 1) && a,{}); // https://stackoverflow.com/a/58600923/295783
const process = file => {
const sentences = file.split(/\r?\n/);
const palindromes = sentences.map(word => clean(word).toLowerCase()).filter(palindrome); // filter after clean
const freq = palindromes.map(palindrome => ({
palindrome,freq: frequency(palindrome)
}));
const freqAll = frequency(palindromes.join(""))
console.log('all sentences:',sentences);
console.log('only palindromes:',palindromes);
console.log(freq);
console.log("All",freqAll);
}
// replace the test result below with your file getting
const result = `mom
Racecar!
another line`
process(result); // goes into the success of the file getting
替换以 const result
开头的行,直到以
window.addEventListener('load',function() {
document.getElementById("myBtn").addEventListener("click",function() {
const reader = new FileReader();
reader.addEventListener('load',function() { process(this.result) });
reader.readAsText(document.querySelector('input').files[0]);
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。