无法解决 clojure.string/replace“不是函数”错误

dig*_*jim 3 replace clojurescript

这是 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))))
Run Code Online (Sandbox Code Playgroud)

正如您在这一行中看到的:[s match replacement],此方法接受三个参数。

从我的 REPL:

user=> (replace ":c41120" ":" "")

ArityException Wrong number of args (3) passed to: core/replace  clojure.lang.AFn.throwArity (AFn.java:429)
Run Code Online (Sandbox Code Playgroud)

我是唯一一个认为我通过了正确数量的参数 (3) 的人吗?知道为什么这会失败吗?

问题,第二部分:具体化

在我的 components.cljs 文件中,我有这些“要求”:

(ns labrador.components
(:require [re-frame.core :as rf]
          [reagent.core :refer [atom]]
          [clojure.string :as s]
          [labrador.helpers :as h]))
Run Code Online (Sandbox Code Playgroud)

我已经成功使用“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 ":" "")]
Run Code Online (Sandbox Code Playgroud)

...我收到以下错误:

Uncaught TypeError: s.replace is not a function
  at clojure$string$replace (string.cljs?rel=1489020198332:48)
  at components.cljs?rel=1489505254528:484
Run Code Online (Sandbox Code Playgroud)

...当我显式调用替换函数时,如下所示:

code (clojure.string/replace key ":" "")]
Run Code Online (Sandbox Code Playgroud)

...我仍然得到完全相同的错误,就好像我仍在调用“s/replace”一样。

我是 Clojure/ClojureScript 的新手,所以我显然无知。

Dan*_*ton 5

首先,看起来您运行的是 Clojure REPL,而不是 ClojureScript,其次,您调用的是clojure.core/replace,而不是clojure.string/replace


dig*_*jim 5

我发现了错误。我试图替换一个键,而不是一个字符串。一旦我在调用替换函数之前将键转换为字符串,通过更改(s/replace key ":" "")with (s/replace (str key) ":" ""),一切都很好。

模棱两可的错误消息使我偏离了路线。被告知函数 'replace' 显然不是一个函数,而不是被告知该函数无法执行它的工作,因为传递的数据不是字符串,只是花费了我大约三个小时的开发时间。

  • 如果您试图从没有前导 : 的关键字中获取字符串,则可以使用 `name` 函数。 (2认同)