简体   繁体   English

学习编程JavaScript,但我被困住了

[英]Learning to programming JavaScript, but I'm stuck

Yesterday I started learning JavaScript. 昨天我开始学习JavaScript。 I am using the system Codecademy , but I'm stuck. 我正在使用系统Codecademy ,但遇到问题 When I say "stuck", I mean I have assignment with which I cannot see what is wrong. 当我说“卡住”时,我的意思是我有作业,看不到哪里出了问题。

The assignment is: 分配是:

Create an array, myArray . 创建一个数组myArray Its first element should be a number, its second should be a boolean, its third should be a string, and its fourth should be...an object! 它的第一个元素应该是数字,第二个应该是布尔值,第三个应该是字符串,第四个应该是...一个对象! You can add as many elements of any type as you like after these first four. 您可以在前四个之后添加任意数量的任意类型的元素。

This is the code I made: 这是我编写的代码:

var myObj = {
    name: 'Hansen'
};

var myArray = [12,true, "Steen" ,myObj.name];

The error: 错误:

Oops, try again. 糟糕,再试一次。 Is the fourth element of myArray an object? myArray的第四个元素是对象吗?

Hope you can help me. 希望您能够帮助我。

The problem with your fourth element is you are passing a string because myObj.name is defined as Hansen . 第四个元素的问题是您正在传递字符串,因为myObj.name被定义为Hansen Pass the object instead: 传递对象:

var myArray = [12,true, "Steen" ,myObj];

I don't know that site, but you can do: 我不知道该网站,但您可以这样做:

var myArray = [
    12,
    true,
    "Steen",
    {name: 'Hansen'}
];

What you are passing to the array is the value of the name property of your object instead of the object itself. 您传递给数组的是对象的name属性的值,而不是对象本身。

Your passing in the name property instead of the object for the fourth array parameter as you probably already know from the other anwers. 您可能已经从其他答案中知道了,您传入了name属性而不是第四个数组参数的对象。

As your learning here are a few ways to do exactly the same thing as your accomplishing here. 在这里学习时,有几种方法可以与在此完成的事情完全相同。

Your way corrected: 您的方式已纠正:

var myObj = {
    name: 'Hansen'
};

var myArray = [12, true, "Steen", myObj];

Other ways: 其他方法:

// Method 1
var myArray = [12, true, "Steen", {name: 'Hansen'}];

// Method 2
var myObj = new Object();
myObj.name = "Hansen";
var myArray = new Array(12, true, "Steen", myObj);

// Method 3
var myObj = {};
myObj['name'] = 'Hansen'
var myArray = [
    12, true, 'Steen', myObj
]

Each method shows a few different ways to do the same thing, you can mix and match the equivalent parts of code to get the same job done. 每种方法都显示几种不同的方法来完成相同的工作,您可以混合并匹配等效的代码部分来完成相同的工作。 It's basically inter changing between the normal JavaScript syntax and object literal syntax . 在普通的JavaScript语法和对象文字语法之间基本上是相互转换的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM