ทำไมฉันถึงได้ ...
Uncaught TypeError: string.split ไม่ใช่ฟังก์ชัน
... เมื่อฉันวิ่ง ...
var string = document.location;
var split = string.split('/');
ทำไมฉันถึงได้ ...
Uncaught TypeError: string.split ไม่ใช่ฟังก์ชัน
... เมื่อฉันวิ่ง ...
var string = document.location;
var split = string.split('/');
คำตอบ:
เปลี่ยนสิ่งนี้ ...
var string = document.location;
สำหรับสิ่งนี้...
var string = document.location + '';
นี้เป็นเพราะdocument.locationเป็นวัตถุสถานที่ตั้ง ค่าเริ่มต้น.toString()จะส่งคืนตำแหน่งในรูปแบบสตริงดังนั้นการต่อข้อมูลจะทำให้เกิดสิ่งนั้น
คุณยังสามารถใช้document.URLเพื่อรับสตริง
toString()แทนการเชื่อมต่อแบบแฮ็ก?
+ ''เป็นเคล็ดลับทั่วไปสำหรับการบีบบังคับสตริง แต่บางคนชอบtoString()วิธีนี้ ฉันจะไม่คิดว่ามันแฮ็คมากไปกว่าการใช้ยูนารี+สำหรับการแปลงตัวเลข
parseInt()และparseFloat(). Number()นอกจากนี้ยังมี +สั้นแน่นอน แต่สามารถอ่านได้น้อยสำหรับคนที่ไม่ได้ใช้รหัส hacky หรือมีประสบการณ์น้อย
+ ''วิธีการไม่ได้เปลี่ยนแปลงอะไรสำหรับฉันใน Chrome เบราว์เซอร์ แต่toString()ไม่
อาจจะ
string = document.location.href;
arrayOfStrings = string.toString().split('/');
สมมติว่าคุณต้องการ url ปัจจุบัน
เรียกใช้สิ่งนี้
// you'll see that it prints Object
console.log(typeof document.location);
คุณต้องการdocument.location.toString()หรือdocument.location.href
document.location ไม่ใช่สตริง
คุณอาจต้องการใช้document.location.hrefหรือdocument.location.pathnameแทน
ใน clausule ()ถ้าใช้ ตัวอย่างเช่น:
stringtorray = "xxxx,yyyyy,zzzzz";
if (xxx && (stringtoarray.split(',') + "")) { ...
document.locationเป็นวัตถุ ลอง:var string=document.location.href