将数组(作为函数参数传递)元素复制到JavaScript中的另一个本地数组中

时间:2018-03-03 09:48:20

标签: javascript arrays

我有以下代码:

(function (window) {
  function javJavScript() {
    var _javJavObject = {};
    var elemImg = [];

    _javJavObject.myCustomLog = function (thingToLog) {
      console.log("My-Custom-Log > Type of variable : " + typeof (thingToLog));
      console.log("My-Custom-Log > Is number : " + !isNaN(thingToLog));
      console.log("My-Custom-Log > Length : " + (thingToLog).length);

      return console.log(thingToLog);
    };

    _javJavObject.imageArrayRandomizer = function (elementID, elemImg) {
      var imgArray = [];
      var i = imgArray.length;
      var cloneElemImg = elemImg.slice(0);
      for (i = 0; i < imgArray.length; i++) {
        imgArray[i] = elemImg[i];
      }
      document.write(imgArray[0]);
      document.write("<br>" + elemImg[0]);
      var elemBG = document.getElementById(elementID);
      if (i) {
        elemBG.style.background = imgArray[Math.floor(Math.random() * i)];
      }
    };



    return _javJavObject;
  }


  if (typeof (window.javJavScript) === 'undefined') { window.javJavScript = javJavScript(); }
})(window);



javJavScript.imageArrayRandomizer('my-body', ["blue", "red", "green", "yellow"]);

我调用imageArrayRandomizer函数,看到imgArray[0]undefinedelemImg[0]为“蓝色”(应该是)。我在这里读了关于我的问题的其他问题 - 他们建议使用apply()或splice()方法,但我可能没有正确使用它们,因为我无法得到我想要的结果。我究竟做错了什么?

1 个答案:

答案 0 :(得分:0)

for (i = 0; i < imgArray.length; i++)

imgArray为空,因此for循环不会运行。可以这样做:

for (i = 0; i < elemImg.length; i++)