以下のコードを参照してください。 01 let obj = { 02 foo: 1, 03 bar: 2 04 } 05 let output = [] 06 07 for (let something of obj) { 08 output.push(something); 09 } 10 11 console.log(output); 11行目の出力値は何ですか?
正解:A
The key line is: for (let something of obj) { In JavaScript: * for...of is used to iterate over iterable objects, such as: * Arrays * Strings * Maps * Sets * Other objects that implement a [Symbol.iterator] method. Plain JavaScript objects created with object literal {} are not iterable by default . They do not have [Symbol. iterator], so using for...of directly on them causes a runtime error. Specifically: for (let something of obj) { ... } will throw a TypeError similar to: obj is not iterable Therefore, the loop body never executes, and console.log(output); is never reached without an error. Why other options are incorrect: * B. [1, 2] * To get [1, 2], you could use Object.values(obj) and iterate that array. * But here, for...of obj never yields values because it throws an error. * C. [ " foo " , " bar " ] * To get property names, you could use Object.keys(obj) with for...of. * Again, the code does not do that; it incorrectly tries to iterate the object directly. * D. [ " foo:1 " , " bar:2 " ] * You would need both keys and values, combining them manually. * The given code does not implement such logic and fails before pushing anything into output. Hence, the correct answer is: The answer: A Study Guide / Concept References (no links): * Difference between for...of and for...in * Iterables in JavaScript and [Symbol.iterator] * Plain objects {} are not iterable by default * Correct patterns to iterate object keys/values (Object.keys, Object.values, Object.entries)