gpt4 book ai didi

javascript - ClojureScript 中的向量到元素?

转载 作者:行者123 更新时间:2023-11-28 19:01:37 25 4
gpt4 key购买 nike

我有一个向量:

(def my-collection ["image1.jpg" "image2.jpg" "image3.jpg"])

我想在文档中制作 3 张图像。

(println (count my-collection)) ; this prints count of my collection. This is 3.

(map (fn [x] (println x)) my-collection) ; doesn't do anything!

但是!

(def image-element (.createElement js/document "img"))
(def insert-into-body (.appendChild (.-body js/document) image-element))
(set! (.-src image-element) "image1.jpg")

这段代码非常适合一个元素!

我应该为收藏做什么?

最佳答案

map 函数用于通过应用指定的函数将一个集合转换为另一个集合。由于 (println x) 返回 nil,因此代码的结果将是 (nil, nil, nil) 并带有副作用(每个图像名称打印在您的控制台中)。

也许您想定义一个函数来创建具有指定 src 的图像元素。

(defn create-image [src]
(let [img (.createElement js/document "img")]
(set! (.-src img) src)
img))

现在,您可以提供集合将图像名称映射到图像元素,然后将它们附加到 body 元素中。

(doseq [i (map create-image my-collection)]
(.appendChild (.-body js/document) i))

关于javascript - ClojureScript 中的向量到元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32434643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com