我不明白為什么當我回傳時element.toUpperCase()
它不會以大寫形式回傳到陣列,但是如果我console.log(element.toUpperCase())在回傳陳述句之前它顯示為大寫
const sentence = "fur pillows are hard to actually sleep on";
const uppercaseOddWords = (string) => {
string = string.split(" ");
oddWords = string.filter((element, index) => {
if (index % 2 === 0) {
return element;
}
return element.toUpperCase();
});
console.log(oddWords.join(" "));
};
uppercaseOddWords(sentence);
uj5u.com熱心網友回復:
filter回呼預期回傳truthy或falsy值,在您的情況下,所有值都是truthy并且不會filter是任何東西,您正在尋找的是map方法。
const sentence = "fur pillows are hard to actually sleep on";
const uppercaseOddWords = (string) => {
string = string.split(" ");
oddWords = string.map((element, index) => {
if (index % 2 === 0) {
return element;
}
return element.toUpperCase();
});
console.log(oddWords.join(" "));
};
uppercaseOddWords(sentence);
uj5u.com熱心網友回復:
.filter()僅當您想選擇陣列的元素并根據布爾邏輯測驗省略某些內容時才應使用。該函式需要一個邏輯條件,并且可以回傳true或false。您使用的功能錯誤。
.map()另一方面,用于根據函式中的邏輯將陣列中的元素從其原始狀態轉換為任何其他狀態。
const sentence = "fur pillows are hard to actually sleep on";
const uppercaseOddWords = (string) => {
const words = string.split(" ");
const oddWords = words.map((word, index) => {
if (index % 2 === 0) {
return word;
}
return word.toUpperCase();
});
console.log(oddWords.join(" "));
};
uppercaseOddWords(sentence);
uj5u.com熱心網友回復:
仍然想知道為什么回傳它不起作用,但我得到了以這種方式作業的功能;
const sentence = "fur pillows are hard to actually sleep on";
const uppercaseOddWords = (string) => {
let newString = "";
string = string.split(" ");
string.filter((element, index) => {
if (index % 2 === 0) {
return (newString = element " ");
}
return (newString = element.toUpperCase() " ");
});
console.log(newString.trim()); //remove trailing spaces
};
uppercaseOddWords(sentence);
uj5u.com熱心網友回復:
您可以通過使用Array.map()將回傳與傳遞的相同數量的元素的方法來實作這一點,基于奇數元素的條件,我們可以將奇數元素轉換為大寫。
現場演示:
const sentence = "fur pillows are hard to actually sleep on";
const uppercaseOddWords = (string) => {
string = string.split(" ");
const res = string.map((element, index) => (index % 2 === 0) ? element.toUpperCase() : element);
console.log(res.join(" "));
};
uppercaseOddWords(sentence);
uj5u.com熱心網友回復:
根據@Mina 的回答,我將其更改為單線
const sentence = "fur pillows are hard to actually sleep on";
const uppercaseOddWords = (string) => string.split(" ").map((d,i) => i%2==0 ? d: d.toUpperCase()).join(" ");
console.log(uppercaseOddWords(sentence));
更新:如果要使用filter(),則需要回傳所有元素并動態更改元素
const sentence = "fur pillows are hard to actually sleep on";
const uppercaseOddWords = (string) => {
let data= string.split(" ");
data.filter((element, index) => {
if (index % 2 != 0) {
data[index] = element.toUpperCase() // we can use index to change the element to uppercase
}
return true; // return all the elements
});
data = data.join(" ")
console.log(data);
return data
};
uppercaseOddWords(sentence);
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/517892.html
標籤:javascript细绳
上一篇:python-如何將用空格分隔的列中的字串劃分為PythonPandas中DataFrame中的3個新列?
下一篇:優化校驗值
