我有以下代码:
(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]
为undefined
而elemImg[0]
为“蓝色”(应该是)。我在这里读了关于我的问题的其他问题 - 他们建议使用apply()或splice()方法,但我可能没有正确使用它们,因为我无法得到我想要的结果。我究竟做错了什么?
答案 0 :(得分:0)
for (i = 0; i < imgArray.length; i++)
好imgArray
为空,因此for循环不会运行。可以这样做:
for (i = 0; i < elemImg.length; i++)