javascript创建一个对象来打印一个数组对象

时间:2013-12-13 21:46:38

标签: javascript

我是javascript的新手并尝试打印创建包含数组的对象并打印数组, 当我尝试运行此代码时,我在控制台中出现错误 - 语法错误丢失;靠近“var person-1”

<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
        </script>
        <script>
            $(document).ready(function(){
                function person(fname,lname,kids){
                    this.firstname = fname;
                    this.lastname = lname;
                    this.kids = kids;
                    this.displaykids = function displaykids(){
                        this.kids.forEach(function(kid){
                            console.log(kid);
                        })
                    }
                }
                var person-1 = person('Bob','Marley',['Bill','Mike','Tom'])
                console.log(person.firstname)
            })
        </script>
    </head>
    <body>
        This is the body
    </body>
</html>

1 个答案:

答案 0 :(得分:1)

var person-1 = person('Bob','Marley',['Bill','Mike','Tom'])

这里有两件事不对。一:变量中不能有-。二:你忘记了new

应该是:

var person1 = new person('Bob','Marley',['Bill','Mike','Tom']);
console.log(person1.firstname);