JavaScript中的对象操作

Object Manipulation in JavaScript

本文关键字:操作 对象 JavaScript      更新时间:2023-09-26

我想显示对象Wine1的所有属性

<html>
    <head>
    </head>
    <body>
        <input type="button" value="Button" onClick="f1()">
        <script type="text/javascript">
            function f1()
            {
                var Wine1=new Object();
                Wine1.color="Red";
                Wine1.price="50000 USD";
                Wine1.vine-yard="South";
                var record="Wine1<br><br>";
                for(var prop in Wine1)
                {
                    record+=prop+"="+Wine1[prop]+"<BR>";
                }
                record+="<br>";
                document.write(record);
            }
        </script>
    </body>
</html>

谁来帮我找出错误

Wine1.vine-yard

vine-yard是无效的标识符。它可能会抛出语法错误。基本上,标识符只接受_$和字母数字字符。标识符是属性名或变量名。

同样,你的循环可能会显示你所定义的属性之外的其他属性。长话短说,以下是你需要做的:

for (var prop in Wine1) {
    if (Wine1.hasOwnProperty(prop)) {
        record += prop + "=" + Wine1[prop] + "<BR>";
    }
}

最后,使用正确的缩进和空格。阅读你的代码,看看哪里出了问题真的很有帮助。