要避免JavaScript中split方法的常見錯誤,您可以遵循以下建議:
let str = "apple,banana,orange";
let fruits = str.split(","); // fruits will be ["apple", "banana", "orange"]
let str = "apple.banana.orange";
let fruits = str.split("\\."); // fruits will be ["apple", "banana", "orange"]
let str = "apple|banana|orange";
let fruits = str.split("|"); // fruits will be ["apple", "banana", "orange"]
let str = "";
let fruits = str.split(","); // fruits will be [""]
if (fruits.length === 1 && fruits[0] === "") {
// Handle the empty string case
}
let separator = ",";
let str = "apple,banana,orange";
let fruits = str.split(separator); // fruits will be ["apple", "banana", "orange"]
遵循這些建議可以幫助您避免JavaScript中split方法的常見錯誤。