我有這個專案,我在其中創建了一個鏈接,其中包含多個用 & 符號連接的陣列。它作業得很好,但是當我得到超過 3 個陣列時,它就不行了。當我跳過幾個問題時,我會在字串的開頭得到一個 & 符號,而當我只選擇第一個問題時,它會在末尾添加一個,這很糟糕。另外,如果我選擇第一個和最后一個陣列并跳過其余的陣列,則在兩者之間添加一個倍數,而我總是只想要 1。
我用它來加入陣列:
/**
* Returns the parameters for the URL.
*
* @returns {string}
*/
getLink() {
this.tmp = [];
for (let i = 0; i < this.url.length; i ) {
// Check if question is from the same quiz part and adds a , between chosen answers and add the right prefix at the beginning
if (this.url[i].length > 0) {
this.tmp.push("" Quiz[i].prefix this.url[i].join(","))
}
// if the link is empty remove everything that was added (& an ,)
if (this.url[i].length === 0) {
this.tmp.push("");
}
}
/// If answers are from different quiz parts add a & between answers
return "" this.tmp.join("&");
}
Quiz 和 this.url 是陣列, .prefix 和 stuff 是陣列的鍵。
這是我用來檢查鏈接字串以洗掉不需要的 & 符號的方法:
LinkChecker(link) {
let cleanLink = link.split('&&').join('&');
if (cleanLink[0] === '&') {
cleanLink = cleanLink.slice(1);
}
if (cleanLink[cleanLink.length - 1] === '&') {
cleanLink = cleanLink.slice(0, -1);
}
return cleanLink;
console.log(cleanLink.length)
}
這是我現在嘗試的:
let i = 0;
let LastLink = '';
let FirstLink = LastLink;
let link = this.LinkChecker(this.getLink());
if (link[link.length -1] === '&'){
LastLink = link.slice(0, -1);
}
while(i == '&'){
if(LastLink[i] === '&'){
FirstLink = link.slice(-1, 0);
}
i
}
console.log(FirstLink)
但這也不起作用。
預習:
bd_shoe_size_ids=6621&&&
&&manufacturer_ids=5866
bd_shoe_size_ids=6598&&&manufacturer_ids=5866
It's supposed to look like:
bd_shoe_size_ids=6598&manufacturer_ids=5866
uj5u.com熱心網友回復:
最好避免而不是修復(雙&)。
洗掉整個塊push("")。這個推送是在你的陣列中添加一個你根本不想擁有的條目,所以不要推送它。
uj5u.com熱心網友回復:
你的LinkChecker方法只考慮&s對。&您可以通過拆分和過濾掉陣列中的任何空條目來處理任意數量的s:
LinkChecker(link) {
// split by & and then filter out the blank entries
let cleanLink = link
.split('&')
.filter((section) => section !== '') // remove any empty strings
.join('&');
if (cleanLink[0] === '&') {
cleanLink = cleanLink.slice(1);
}
if (cleanLink[cleanLink.length - 1] === '&') {
cleanLink = cleanLink.slice(0, -1);
}
return cleanLink;
console.log(cleanLink.length)
}
正如其他人所提到的,有一些方法可以在您的陣列創建中解決這個問題,但是由于您的 LinkChecker 似乎是您專門清理它們的地方,我只是為了清楚起見而更改了該方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/438961.html
標籤:javascript arrays function duplicates
上一篇:將函式值回傳給變數
下一篇:使用帶有默認初始化程式的多載函式
