นี่คือบล็อกโค้ดดั้งเดิมสำหรับฟังก์ชันสตริง "แทนที่" ของ ClojureScript:
(defn replace
"Replaces all instance of match with replacement in s.
match/replacement can be:
string / string
pattern / (string or function of match)."
[s match replacement]
(cond
(string? match)
(.replace s (js/RegExp. (gstring/regExpEscape match) "g") replacement)
(instance? js/RegExp match)
(if (string? replacement)
(replace-all s match replacement)
(replace-all s match (replace-with replacement)))
:else (throw (str "Invalid match arg: " match))))
ดังที่คุณเห็นในบรรทัดนี้:[s match replacement]
วิธีนี้ยอมรับสามอาร์กิวเมนต์
จาก REPL ของฉัน:
user=> (replace ":c41120" ":" "")
ArityException Wrong number of args (3) passed to: core/replace clojure.lang.AFn.throwArity (AFn.java:429)
ฉันเป็นคนเดียวที่คิดว่าฉันผ่านการโต้แย้งตามจำนวนที่ถูกต้อง (3) หรือไม่? มีความคิดใดบ้างว่าทำไมสิ่งนี้ถึงล้มเหลว?
คำถาม ตอนที่ 2: เจาะจง
ในไฟล์ส่วนประกอบ cljs ของฉัน ฉันมี 'ข้อกำหนด' เหล่านี้:
(ns labrador.components
(:require [re-frame.core :as rf]
[reagent.core :refer [atom]]
[clojure.string :as s]
[labrador.helpers :as h]))
ฉันประสบความสำเร็จในการใช้ "s/join" และ "s/blank?" ในไฟล์นี้ แต่เมื่อฉันลองใช้ "s/replace" เหมือนด้านล่าง (โปรดทราบว่าการโทร "replace" อยู่ในสาย 484):
(for [roll-count order-item-roll-counts]
(let [key (key roll-count)
val (val roll-count)
code (s/replace key ":" "")]
...ฉันได้รับข้อผิดพลาดต่อไปนี้:
Uncaught TypeError: s.replace is not a function
at clojure$string$replace (string.cljs?rel=1489020198332:48)
at components.cljs?rel=1489505254528:484
...และเมื่อฉันเรียกใช้ฟังก์ชันการแทนที่อย่างชัดเจน เช่น:
code (clojure.string/replace key ":" "")]
...ฉันยังคงได้รับข้อผิดพลาดเดิมทุกประการ ราวกับว่าฉันยังคงโทรหา "s/replace"
ฉันยังใหม่กับ Clojure/ClojureScript เลยเปลือยเปล่าด้วยความไม่รู้ที่ชัดเจนของฉัน