Files
2022-01-20 20:30:18 +01:00

3.1 KiB

id, title, challengeType, videoUrl, forumTopicId, dashedName
id title challengeType videoUrl forumTopicId dashedName
56533eb9ac21ba0edf2244c9 変数によるオブジェクトのプロパティへのアクセス 1 https://scrimba.com/c/cnQyKur 16165 accessing-object-properties-with-variables

--description--

オブジェクトに対するブラケット記法のもう一つの用例として、プロパティを変数の値として保存し、アクセスする方法があります。 この用法は、オブジェクトのプロパティを繰り返し処理する場合や、ルックアップテーブルにアクセスする場合にとても便利です。

次は変数を使用してプロパティにアクセスする例です。

const dogs = {
  Fido: "Mutt",
  Hunter: "Doberman",
  Snoopie: "Beagle"
};

const myDog = "Hunter";
const myBreed = dogs[myDog];
console.log(myBreed);

コンソールには文字列 Doberman が表示されます。

この用法の別の例として、プログラムの実行中にプロパティの名前を動的に取得することができます。次に例を示します。

const someObj = {
  propName: "John"
};

function propPrefix(str) {
  const s = "prop";
  return s + str;
}

const someProp = propPrefix("Name");
console.log(someObj[someProp]);

someProp の値は文字列 propName となり、文字列 John がコンソールに表示されます。

変数を使用してプロパティにアクセスする場合、変数名を引用符で囲まないことに注意してください。使用するのは変数のであって、名前ではありません。

--instructions--

playerNumber 変数を 16 に設定してください。 次に、変数を使用してプレイヤーの名前を参照し、それを player に割り当ててください。

--hints--

playerNumber は数値である必要があります。

assert(typeof playerNumber === 'number');

変数 player は文字列である必要があります。

assert(typeof player === 'string');

player の値は文字列 Montana である必要があります。

assert(player === 'Montana');

ブラケット記法を使用して testObj にアクセスする必要があります。

assert(/testObj\s*?\[.*?\]/.test(code));

Montana を、変数 player に直接、割り当てることはできません。

assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));

ブラケット記法で、変数playerNumber を使用する必要があります。

assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));

--seed--

--after-user-code--

if(typeof player !== "undefined"){(function(v){return v;})(player);}

--seed-contents--

// Setup
const testObj = {
  12: "Namath",
  16: "Montana",
  19: "Unitas"
};

// Only change code below this line
const playerNumber = 42;  // Change this line
const player = testObj;   // Change this line

--solutions--

const testObj = {
  12: "Namath",
  16: "Montana",
  19: "Unitas"
};
const playerNumber = 16;
const player = testObj[playerNumber];