mirror of
https://github.com/freeCodeCamp/freeCodeCamp.git
synced 2026-01-28 18:01:48 -05:00
108 lines
2.6 KiB
Markdown
108 lines
2.6 KiB
Markdown
---
|
||
id: 56533eb9ac21ba0edf2244c9
|
||
title: Доступ до властивостей об'єкту за допомогою змінних
|
||
challengeType: 1
|
||
videoUrl: 'https://scrimba.com/c/cnQyKur'
|
||
forumTopicId: 16165
|
||
dashedName: accessing-object-properties-with-variables
|
||
---
|
||
|
||
# --description--
|
||
|
||
Ще одне використання дужкової нотації на об'єктах полягає в доступі до властивостей, які зберігаються у вигляді змінної величини. Це може бути дуже корисним для ітерації властивостей об'єкта або при отриманні доступу до пошукової таблиці.
|
||
|
||
Ось приклад використання змінної для отримання доступу до властивостей:
|
||
|
||
```js
|
||
const dogs = {
|
||
Fido: "Mutt",
|
||
Hunter: "Doberman",
|
||
Snoopie: "Beagle"
|
||
};
|
||
|
||
const myDog = "Hunter";
|
||
const myBreed = dogs[myDog];
|
||
console.log(myBreed);
|
||
```
|
||
|
||
У консолі відображатиметься рядок `Doberman`.
|
||
|
||
Note that we do *not* use quotes around the variable name when using it to access the property because we are using the *value* of the variable, not the *name*.
|
||
|
||
# --instructions--
|
||
|
||
Set the `playerNumber` variable to `16`. Then, use the variable to look up the player's name and assign it to `player`.
|
||
|
||
# --hints--
|
||
|
||
`playerNumber` should be a number
|
||
|
||
```js
|
||
assert(typeof playerNumber === 'number');
|
||
```
|
||
|
||
The variable `player` should be a string
|
||
|
||
```js
|
||
assert(typeof player === 'string');
|
||
```
|
||
|
||
The value of `player` should be the string `Montana`
|
||
|
||
```js
|
||
assert(player === 'Montana');
|
||
```
|
||
|
||
You should use bracket notation to access `testObj`
|
||
|
||
```js
|
||
assert(/testObj\s*?\[.*?\]/.test(code));
|
||
```
|
||
|
||
You should not assign the value `Montana` to the variable `player` directly.
|
||
|
||
```js
|
||
assert(!code.match(/player\s*=\s*"|\'\s*Montana\s*"|\'\s*;/gi));
|
||
```
|
||
|
||
You should be using the variable `playerNumber` in your bracket notation
|
||
|
||
```js
|
||
assert(/testObj\s*?\[\s*playerNumber\s*\]/.test(code));
|
||
```
|
||
|
||
# --seed--
|
||
|
||
## --after-user-code--
|
||
|
||
```js
|
||
if(typeof player !== "undefined"){(function(v){return v;})(player);}
|
||
```
|
||
|
||
## --seed-contents--
|
||
|
||
```js
|
||
// 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--
|
||
|
||
```js
|
||
const testObj = {
|
||
12: "Namath",
|
||
16: "Montana",
|
||
19: "Unitas"
|
||
};
|
||
const playerNumber = 16;
|
||
const player = testObj[playerNumber];
|
||
```
|