--- id: 587d7b7c367417b2b2512b1a title: Access Property Names with Bracket Notation challengeType: 1 videoUrl: '' localeTitle: 使用括号表示法访问属性名称 --- ## Description
在第一个对象挑战中,我们提到使用括号表示法作为使用变量求值来访问属性值的方法。例如,假设我们的foods对象被用于超市收银机的程序中。我们有一些设置selectedFood功能,我们想检查我们的foods对象是否存在该食物。这可能看起来像:
let selectedFood = getCurrentFood(scanningItem);
让库存=食物[selectedFood];
此代码将评估存储在selectedFood变量中的值,并在foods对象中返回该键的值,如果不存在则返回undefined 。括号表示法非常有用,因为有时候对象属性在运行时之前是未知的,或者我们需要以更动态的方式访问它们。
## Instructions
我们定义了一个函数checkInventory ,它接收一个扫描的项目作为参数。返回foods对象中的scannedItem键的当前值。您可以假设只有有效键将作为checkInventory的参数提供。
## Tests
```yml tests: - text: checkInventory是一个函数 testString: 'assert.strictEqual(typeof checkInventory, "function", "checkInventory is a function");' - text: 'foods对象应该只有以下键值对: apples: 25oranges: 32plums: 28bananas: 13grapes: 35strawberries: 27' testString: 'assert.deepEqual(foods, {apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27}, "The foods object should have only the following key-value pairs: apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27");' - text: checkInventory("apples")应该返回25 testString: 'assert.strictEqual(checkInventory("apples"), 25, "checkInventory("apples") should return 25");' - text: checkInventory("bananas")应该返回13 testString: 'assert.strictEqual(checkInventory("bananas"), 13, "checkInventory("bananas") should return 13");' - text: checkInventory("strawberries")应该返回27 testString: 'assert.strictEqual(checkInventory("strawberries"), 27, "checkInventory("strawberries") should return 27");' ```
## Challenge Seed
```js let foods = { apples: 25, oranges: 32, plums: 28, bananas: 13, grapes: 35, strawberries: 27 }; // do not change code above this line function checkInventory(scannedItem) { // change code below this line } // change code below this line to test different cases: console.log(checkInventory("apples")); ```
## Solution
```js // solution required ```