[英]Javascript prevent redundancy when joining multiple arrays
我有一個創建長鏈接的 function。 它通過讓人們點擊屬於多個問題的多個答案來做到這一點。 每個問題及其答案都屬於多維數組的一部分。
鏈接創建者:
/**
* Returns the parameters for the URL.
*
* @returns {string}
*/
getLink() {
let quizUrl = control.url[control.questionNumber];
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(","))
// console.log(this.url)
}
if (this.url[i].length === 0) {
this.tmp.push("");
}
// console.log(quizUrl.length)
console.log(this.tmp);
}
/// If answers are from different quiz parts add a & between answers.
return "" + this.tmp.join("&");
};
大批:
class QuizPart {
constructor(questionText, chosenAnswer, prefix, questionDescription) {
this.questionText = questionText;
this.chosenAnswer = chosenAnswer;
this.prefix = prefix;
this.questionDescription = questionDescription;
}
}
class ChosenAnswer {
constructor(id, name) {
this.id = id;
this.name = name;
}
}
let Quiz = [
new QuizPart('Whats your size?', [
new ChosenAnswer('6595', '41'),
new ChosenAnswer('6598', '42'),
new ChosenAnswer('6601', '43'),
new ChosenAnswer('', ''),
], 'bd_shoe_size_ids=',
'The size of your shoes is very important. If you have the wrong size, they wont fit.'),
new QuizPart('What color would you like?', [
new ChosenAnswer('6053', 'Red'),
new ChosenAnswer('6044', 'Blue'),
new ChosenAnswer('6056', 'Yellow'),
new ChosenAnswer('6048', 'Green'),
new ChosenAnswer('', ''),
], 'color_ids=',
'Color isn t that important, It looks good tho.'),
new QuizPart('What brand would you like?', [
new ChosenAnswer('5805', 'Adidas'),
new ChosenAnswer('5866', 'Nike'),
new ChosenAnswer('5875', 'Puma'),
new ChosenAnswer('', ''),
], 'manufacturer_ids=',
'Brand is less important. Its just your own preference'),
]
每次您將 go 轉到 getLink() 中的一個新問題時,它都會用 & 連接這兩個問題。 當您控制台記錄 getLink() 時,它看起來像這樣:
bd_shoe_size_ids=6595&color_ids=6044&manufacturer_ids=5875,5866
但是,如果您跳過一個問題,它仍然會添加 & 符號。 因此,如果跳過第一個問題,則開頭有一個 & 符號。 如果我跳過第二個,它會在 middel 中添加 2,如下所示:
bd_shoe_size_ids=6595&&manufacturer_ids=5875
如果你跳過最后一個,它會在最后添加。
我嘗試使用 replace 僅用一個替換兩個 & 符號,如果它們位於開頭或結尾,則將其刪除,但它不起作用。 如果字符串中沒有值,有人知道不加入他們的好方法嗎?
replace
僅適用於字符串中找到的第一個項目。 您可以使用replaceAll
或split
和join
,這對跨瀏覽器更友好,如下所示:
function cleanLink(link) {
let newLink = link.split('&&').join('&'); // remove duplicate ampersands
if (newLink[0] === '&') {
newLink = newLink.slice(1); // remove starting ampersand
}
if (newLink[newLink.length - 1] === '&') {
newLink = newLink.slice(0,-1); // remove trailing ampersand
}
return newLink;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.