Array.prototype.values()未按MDN示例运行?求原因及可用示例
Troubleshooting Array.prototype.values() Discrepancies with MDN Examples
Hey there! It sounds like you initially hit a confusing spot where you thought MDN's Array.prototype.values() examples weren't working, but later confirmed they run perfectly in your browser (ruling out compatibility issues). Let's unpack what might have caused that initial mismatch, plus share solid, tested examples to reinforce how this method works.
Possible Reasons for Initial Confusion
- Misinterpreting Iterator Output:
values()returns an array iterator object, not a plain array. If you tried logging the iterator directly (likeconsole.log(arr.values())), you'd see an object instead of the array values—this is expected behavior, not a bug. You need to iterate over it to access the actual values. - Accidental Copy-Paste Issues: Sometimes when copying code from docs, tiny formatting glitches (like extra spaces or missing syntax) can break execution. A quick double-check of the code structure usually fixes this.
- Non-Standard Environment Glitches: If you first tested in an outdated code sandbox or environment that overrides native JS methods, that could have caused weird behavior—but since you confirmed it works in your browser, this is less likely.
Working Examples of Array.prototype.values()
Here are a few reliable, runnable examples aligned with MDN's documentation:
1. Basic Iteration with for...of Loop
const fruits = ['apple', 'banana', 'cherry']; const iterator = fruits.values(); for (const value of iterator) { console.log(value); } // Output: // apple // banana // cherry
2. Manually Advancing the Iterator with next()
const numbers = [10, 20, 30]; const numIterator = numbers.values(); console.log(numIterator.next().value); // 10 console.log(numIterator.next().value); // 20 console.log(numIterator.next().value); // 30 console.log(numIterator.next().done); // true (no more values left)
3. Convert Iterator to Plain Array with Spread Syntax
Since the iterator is iterable, you can use the spread operator to turn it into a regular array:
const colors = ['red', 'green', 'blue']; const valuesArray = [...colors.values()]; console.log(valuesArray); // ['red', 'green', 'blue']
Key Notes About Array.prototype.values()
- It’s functionally identical to
Array.prototype[Symbol.iterator]()for arrays—both return an iterator over the array’s values. - It never modifies the original array.
- All modern browsers support this method (as your testing confirmed), so compatibility won’t be an issue unless you’re targeting extremely old browsers like IE, which never supported it.
内容的提问来源于stack exchange,提问作者Ayman Morsy
相关产品推荐
相关产品推荐

