如何解决您能帮我简化几行JavaScript代码吗?
我有一个JavaScript代码,可以通过API获取当前正在播放的歌曲的歌词。
有时候(并非总是如此),歌词会在开始时返回标题,这是我要删除的标题。
示例:
SWEET CHILD O' mine
She's got a smile that it seems to me
Reminds me of childhood memories
Where everything was as fresh as the bright blue sky
Now and then when I see her face
She takes me away to that special place
And if I stare too long,I'd probably break down and cry
........
我想看看它们是否可以帮助我用更少的行来简化代码。
如果您希望所有代码共享,我都会分享我们感兴趣的一部分代码,以帮助您。
currentSong
包含正在播放的歌曲的标题
lyric
包含使用API获取的完整歌词
this.refreshLyric = function(currentSong,currentArtist) {
//another code that does not interest
//...
//...
//lyric variable contains the complete lyrics of a song obtained through an API
var lyric = data.mus[0].text;
//divide the string CurrentSong (contains the song title) into parts
let splitCurrenSong = currentSong.split(' ');
//I get the length of the array
let largeCurrentSong = splitCurrenSong.length;
//divide the string lyric into parts
let splitLyric = lyric.split(' ');
//I get the first elements of the lyric array with the length limit of largeCurrentSong
let pieceLyric = splitLyric.slice(0,largeCurrentSong);
//I get all elements of the splitCurrenSong array
let pieceSong = splitCurrenSong.slice(0,largeCurrentSong);
//join arrays
let joinLyric = pieceLyric.join(' ');
let joinSong = pieceSong.join(' ');
//I check if the chunk of the joinLyric string matches the same chunk of joinSong
if (joinLyric.toLocaleLowerCase() == joinSong.toLocaleLowerCase()) {
//remove the matching items
splitLyric.splice(0,largeCurrentSong);
//put the resulting join array into a variable
lyrics = splitLyric.join(' ');
//remove the spaces from the beginning and end of lyrics
lyric = lyrics.trim()
}
//another code that does not interest
//...
//...
}
编辑:回复@iamaword
如API返回的屏幕快照所示:
text:
包含整首歌曲的歌词
name:
歌曲标题
我可以用以下代码完美地获得歌曲的名称:
var nameSong = data.mus[0].name
但是我认为没有必要,因为我是从currentSong
变量中获得歌曲名称的,这是GET
命令中发送的用于获取歌词的名称。
最终编辑:积分@CerebralFart
完整代码:
this.refreshLyric = function(currentSong,currentArtist) {
var proxy_URL = PROXYURL;
var vagalume_api = 'https://api.vagalume.com.br/search.PHP?';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status === 200) {
var data = JSON.parse(this.responseText);
if (data.type === 'exact' || data.type === 'aprox') {
var lyric = normalizeText(data);
document.getElementById('lyric').innerHTML = lyric.replace(/\n/g,'<br />');
var openLyric = document.getElementsByClassName('lyrics')[0];
openLyric.style.opacity = "1";
openLyric.setAttribute('data-toggle','modal');
var powered = "Vagalume"
var URL_lyric = 'https://www.vagalume.com.br';
//Powered by image src...
const parent = document.querySelector('.chartlyrics');
parent.innerHTML = '';
var img = document.createElement("img");
img.src = "img/103-fundo-escuro.jpg"
img.setAttribute('class',"")
parent.appendChild(img);
parent.appendChild(document.createElement('br'));
parent.append('Powered by ');
// Powered by link a href...
document.getElementById('powered_by').innerHTML = ''
var a = document.getElementById('powered_by')
.appendChild(document.createElement("a"));
a.href = URL_lyric;
a.target = "_blank";
a.rel = "noopener noreferrer";
a.textContent = powered;
} else {
var page = new Page();
page.refreshLyric2(currentSong,currentArtist);
}
} else {
var page = new Page();
page.refreshLyric2(currentSong,currentArtist);
}
}
}
xhttp.open('GET',proxy_URL + vagalume_api + API_KEY + '&art=' + currentArtist + '&mus=' + currentSong.toLowerCase(),true);
xhttp.send()
}
function normalizeText(response){
// First unpack the data,get the right name and text values
let {mus:[{name,text}]} = response;
// Now get the part of the text that might be the title
let titleLength = name.length;
let maybeTitle = text.substring(0,titleLength);
// Compare the two titles and trim if they match
if (name.toLowerCase() === maybeTitle.toLowerCase() && exceptions.includes(maybeTitle.toLowerCase()) == false){
text = text.substring(titleLength)
}
//Remove any leading or trailing whitespace and return
return text.trim();
}
//song names excepted from being removed in lowercase ['one song','two song',etc..]
const exceptions = ['sweet emotion'];
我创建了一个列表,列出了所有歌曲名称,除非它们中的任何一个都将歌曲名称作为歌词的一部分,否则将被删除。
例如著名的Aerosmith-Sweet Emotion歌曲就是这种情况。
Sweet emotion
Sweet emotion
You talk about things and nobody cares
You're wearing other things that nobody wears
You're calling my name but you gotta make clear
I can't say baby where I'll be in a year
.....
我在normalizeText
函数中添加了一个新条件,以检查要删除的歌曲的名称是否不在例外之内。
// Compare the two titles and trim if they match
if (name.toLowerCase() === maybeTitle.toLowerCase() && exceptions.includes(maybeTitle.toLowerCase()) == false){
然后我创建了一个常量exceptions
,其中必须手动添加小写歌曲的名称,并以逗号分隔。
//song names excepted from being removed in lowercase ['one song',etc..]
const exceptions = ['sweet emotion'];
解决方法
有几种清除代码的方法,主要是如何解压缩数据以及如何比较两个字符串。
function normalizeText(response){
// First unpack the data,get the right name and text values
let {mus:[{name,text}]} = response;
// Now get the part of the text that might be the title
let titleLength = name.length;
let maybeTitle = text.substring(0,titleLength);
// Compare the two titles and trim if they match
if (name.toLowerCase() === maybeTitle.toLowerCase()){
text = text.substring(titleLength)
}
//Remove any leading or trailing whitespace and return
return text.trim();
}
编辑:向低级语法错误添加()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。