0

我在下面有这个简单的代码。我正在尝试查询输入框中输入的任何形状的名称。我可以正确地在函数中传递参数,但是当我尝试使用参数查询它时,它会导致我出错。

console.log(shape); //I'm getting the right input as parameter
console.log(shapes.shape.name); //not successful using passed parameter.

//下面的代码

<div id="page">
   <input type="text" id="getShape"/>
   <input type="button" onClick="getShapeDetails()" />
</div>

<script>
   shapes = {
      "circle"   : {"name":"circle", "sides":"0", "color":"yellow"},        
      "triangle" : {"name":"triangle", "sides":"3", "color":"red"},         
      "square"   : {"name":"square", "sides":"4", "color":"blue"},  
   };

   function getShapeDetails(){
      var getShape = document.getElementById("getShape").value;

      function getShapesDetail(shape){
         console.log(shape);
     console.log(shapes.shape.name);
      }

      getShapesDetail(getShape);
   }
</script>
4

2 回答 2

0

试试这个:

console.log(shapes[shape].name);

您想将形状用作形状结构的索引。

于 2013-04-07T16:37:02.320 回答
0

这对我有用:

<html>
    <body>
        <script>
               var shapes = {
                    "circle"   : {"name":"circle", "sides":"0", "color":"yellow"},        
                    "triangle" : {"name":"triangle", "sides":"3", "color":"red"},         
                    "square"   : {"name":"square", "sides":"4", "color":"blue"},  
              };
                console.log("name: ", shapes.circle.color);
        </script>
    </body>

</html>
于 2013-04-07T16:40:23.050 回答