Clourescript:转换数组访问

时间:2016-10-29 07:57:12

标签: clojure clojurescript

问题

我正在尝试转换以下代码:https://github.com/mdn/webgl-examples/blob/gh-pages/tutorial/glUtils.js#L13-L15

JavaScript代码是:

Matrix.Translation = function (v)
{
  // ignore length 2 case for simplicty

  if (v.elements.length == 3) {
    var r = Matrix.I(4);
    r.elements[0][3] = v.elements[0];
    r.elements[1][3] = v.elements[1];
    r.elements[2][3] = v.elements[2];
    return r;
  }

  throw "Invalid length for Translation";
}

现在,我可以按如下方式重写cljs:

(defn translation [x y z]
  (let [r (. js/Matrix I 4)]
     r[0][3] = x ;; how do I write this?
     r[1][3] = y ;; how do I write this?
     r[2][3] = z ;; how do I write this?
  ))

问题

但是,如何在cljs中编写r [0] [3]?

1 个答案:

答案 0 :(得分:1)

您可以使用agetaset来使用Javascript数组:

(def arr (array (array "a1" "a2") (array "b1" "b2") (array "c1" "c2")))

它创建以下嵌套数组:

#js [#js ["a1" "a2"] #js ["b1" "b2"] #js ["c1" "c2"]]

您可以使用aget访问嵌套元素:

(aget arr 1 0)
;; => "b1"

并使用aset更新:

(aset arr 1 0 "newb1")

arr更新为:

#js [#js ["a1" "a2"] #js ["newb1" "b2"] #js ["c1" "c2"]]

您可能需要查看与Javascript数组相关的其他函数:alengtharraymake-arrayarray?