通过显式调用Iterable遍历数组,示例代码如下:
let sampleArr = [4, 3, 56, 7, 7, 8, 9, 9];
let sampleArrIter = sampleArr[Symbol.iterator]();
while (true) {
let iterBody = sampleArrIter.next();
if (iterBody.done) {
//loop ends
break;
} else {
//loop continues - current element - iterBody.value
}
}
我希望能够检测到当前元素是数组中的最后一个元素,以便我可以在循环结束后执行特定的操作。当使用for循环时,我通过比较数组长度和当前索引来做到这一点。如何使用Symbol.iterator做到这一点?
答案 0 :(得分:2)
尝试此代码,可能会对您有所帮助
let sampleArr = [4, 3, 56, 7, 7, 8, 9, 9];
let sampleArrIter = sampleArr[Symbol.iterator]();
let lastIterator = sampleArrIter.next();
let val = lastIterator.value;
while (!lastIterator.done) {
val = lastIterator.value;
lastIterator = sampleArrIter.next();
}
答案 1 :(得分:0)
这是您想要的吗?
let sampleArr = [4, 3, 56, 7, 7, 8, 9, 9];
let sampleArrIter = sampleArr[Symbol.iterator]();
let lastElValue, lastElIndex = -1;
while (true) {
let iterBody = sampleArrIter.next();
if (iterBody.done) {
// do something with last element
console.log(`${lastElValue} : ${lastElIndex}`)
break;
} else {
lastElValue = iterBody.value
lastElIndex++
//loop continues - current element - iterBody.value
}
}