在Javascript中使用Symbol.iterable进行迭代时,如何检测当前元素是最后一个元素?

时间:2018-10-30 07:24:53

标签: javascript arrays loops iterator

通过显式调用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做到这一点?

2 个答案:

答案 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
    }
}