我正在尝试创建接受7位数代码(至少)的函数,然后加载角色的图像/元素,从而从代码中创建一个角色。
我写了这段代码:
<script type="text/javascript">
var skins = [];
skins["w"] = "http://example.com/char_elements/base.png";
var eyes = [];
eyes["b"] = "http://example.com/char_elements/eyes/blue.png";
eyes["g"] = "http://example.com/char_elements/eyes/green.png";
eyes["r"] = "http://example.com/char_elements/eyes/red.png";
var hair = [];
hair["b"] = "http://example.com/char_elements/hair/black.png";
hair["w"] = "http://example.com/char_elements/hair/blond.png";
hair["s"] = "http://example.com/char_elements/hair/brown.png";
var mouth = [];
mouth["h"] = "http://example.com/char_elements/mouth/happy.png";
var pants = [];
pants["s"] = "http://example.com/char_elements/pants/shorts.png";
var shoes = [];
shoes["b"] = "http://example.com/char_elements/shoes/black.png";
var torso = [];
torso["s"] = "http://example.com/char_elements/torso/shirt.png"
function LoadChar(code){
var data = code.split(/(?=[a-z])/i);
var skins = [skins[data[0]], eyes[data[1]], hair[data[2]], mouth[data[3]], pants[data[4]], shoes[data[5]], torso[data[6]]];
document.getElementById("out").innerHTML = skins.toString();
}
</script>
<div id="out"></div>
但是,当我调用LoadChar时(&#34; wgbhsbs&#34;);
它刺激了我&#34;无法阅读财产&#39; w&#39;未定义&#34;
我仍然是JS中的Arrays的新手,所以我确信我正在制作一些简单的语法错误或做一些有点不对的事。
所以它的作用是:
1)接受代码并将其拆分为7个元素(总是7个,没有别的)将其存储在&#34;数据&#34;变量为数组。 2)构建&#34;皮肤&#34;数组加载:skin [代码编号]和其他元素相同。 3)出于测试目的,我试图输出皮肤数组,但它在第2步停止。
对此有任何解释吗?
答案 0 :(得分:5)
您正在重新创建先前定义的skins
变量。
为函数内部的变量使用不同的名称,你会没事的。
var skins = [];
skins["w"] = "http://example.com/char_elements/base.png";
var eyes = [];
eyes["b"] = "http://example.com/char_elements/eyes/blue.png";
eyes["g"] = "http://example.com/char_elements/eyes/green.png";
eyes["r"] = "http://example.com/char_elements/eyes/red.png";
var hair = [];
hair["b"] = "http://example.com/char_elements/hair/black.png";
hair["w"] = "http://example.com/char_elements/hair/blond.png";
hair["s"] = "http://example.com/char_elements/hair/brown.png";
var mouth = [];
mouth["h"] = "http://example.com/char_elements/mouth/happy.png";
var pants = [];
pants["s"] = "http://example.com/char_elements/pants/shorts.png";
var shoes = [];
shoes["b"] = "http://example.com/char_elements/shoes/black.png";
var torso = [];
torso["s"] = "http://example.com/char_elements/torso/shirt.png"
function LoadChar(code){
var data = code.split(/(?=[a-z])/i);
var other_variable = [skins[data[0]], eyes[data[1]], hair[data[2]], mouth[data[3]], pants[data[4]], shoes[data[5]], torso[data[6]]];
alert(other_variable.toString());
}
LoadChar("wgbhsbs");
答案 1 :(得分:1)
您正在定义对象的属性。不是数组。
更改
var skins = [];
skins["w"] = "http://example.com/char_elements/base.png";
到
var skins = {};
skins.w = "http://example.com/char_elements/base.png";
此外,您正在重新定义LoadChar函数中的skins
,正如LcSalazar指出的那样。
<强> Fiddle 强>