将对象属性设置为嵌套属性,函数或数组时出现JS错误

时间:2019-03-17 04:45:41

标签: javascript

使用VSCode尝试JS教程中的示例是JS的新手。当我设置对象属性时遇到此错误。第一个属性,例如firstnamelastnameage看起来不错,但是当我尝试使用数组,函数或嵌套属性作为对象的属性时,出现错误,它将不会登录到控制台。

错误是:

  

“”。“(TS1005)

请告知,完全的菜鸟,但请努力学习更多,所以请原谅我的无知。

   var person = {
       firstname: 'Matilda',
       lastname:'Milner',
       age: 68
       kids: ['Dave', 'Lynn', 'Cal', 'August', 'Cade'],
       location: {
                street: '500 Some St.',
                city: 'Inola',
                state: 'Oklahoma',
                zip: '66702',
                }
        
        fullname: function(){
           return this.firstname + " " + lastname;
        }      
   }
   console.log(person.firstname +" "+person.lastname + " " +"is"+ " " + person.age+ " "+ "years old");
   console.log(person.kids[3])
   console.log(person.address.zip)

1 个答案:

答案 0 :(得分:1)

您的代码中几乎没有语法错误

  • 您在对象定义的很多地方都错过了,
  • 您在this函数中的lastname之前错过了fullname
  • 您没有名为address的任何属性,但您正在尝试访问person.address.zip

var person = {
       firstname: 'Matilda',
       lastname:'Milner',
       age: 68,
       kids: ['Dave', 'Lynn', 'Cal', 'August', 'Cade'],
       location: {
                street: '500 Some St.',
                city: 'Inola',
                state: 'Oklahoma',
                zip: '66702',
                },
        
        fullname: function(){
           return this.firstname + " " + this.lastname;
        }      
   }
   console.log(person.firstname +" "+person.lastname + " " +"is"+ " " + person.age+ " "+ "years old");
   console.log(person.kids[3])
   console.log(person.location.zip)
   console.log(person.fullname())