5

昨日、JavaScript の学習を開始しました。システムCodecademyを使用していますが、行き詰まっています。「行き詰まっている」とは、何が悪いのか分からない課題があることを意味します。

割り当ては次のとおりです。

配列を作成しますmyArray。最初の要素は数値、2 番目の要素はブール値、3 番目の要素は文字列、4 番目の要素は... オブジェクトでなければなりません! これらの最初の 4 つの後に、任意のタイプの要素を好きなだけ追加できます。

これは私が作ったコードです:

var myObj = {
    name: 'Hansen'
};

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

エラー:

おっと、もう一度やり直してください。myArray の 4 番目の要素はオブジェクトですか?

あなたが私を助けてくれることを願っています。

4

3 に答える 3

4

myObj.name4番目の要素の問題は、がとして定義されているため、文字列を渡すことですHansen。代わりにオブジェクトを渡します。

var myArray = [12,true, "Steen" ,myObj];
于 2012-11-23T18:37:18.193 に答える
1

そのサイトはわかりませんが、次のことができます。

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

配列に渡すのはname、オブジェクト自体ではなく、オブジェクトのプロパティの値です。

于 2012-11-23T18:38:32.920 に答える
0

Your passing in the name property instead of the object for the fourth array parameter as you probably already know from the other anwers.

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.

于 2012-11-23T19:40:12.960 に答える