乐趣区

关于javascript:JavaScript专项算法题7Iterators迭代器

@冒泡的马树

题库原地址:http://csbin.io/iterators

Iterators 迭代器

挑战 1

问题:

A) 创立一个 for 循环,用于遍历数组,返回数组的所有元素的总和。

B) 创立一个函数式迭代器,调用时遍历传入的数组的每一个元素,每次一个元素。

题解:

// CHALLENGE 1

function sumFunc(arr) {
  // YOUR CODE HERE
  let sum = 0
  for(let i = 0; i < arr.length; i++) {sum += arr[i]
  }
  return sum
}

// Uncomment the lines below to test your work
const array = [1, 2, 3, 4];
console.log(sumFunc(array)); // -> should log 10

function returnIterator(arr) {
  // YOUR CODE HERE
  let i = 0
  const inner = () => {const element = arr[i]
    i++
    return element
  }
  return inner
}

// Uncomment the lines below to test your work
const array2 = ['a', 'b', 'c', 'd'];
const myIterator = returnIterator(array2);
console.log(myIterator()); // -> should log 'a'
console.log(myIterator()); // -> should log 'b'
console.log(myIterator()); // -> should log 'c'
console.log(myIterator()); // -> should log 'd'

挑战 2

问题:

创立一个附有 next 办法的迭代器。当.next 被调用时,此迭代器会一一返回数组内的元素。

题解:

// CHALLENGE 2

function nextIterator(arr) {
  // YOUR CODE HERE
  let i = 0
  const inner = {next: () => {const element = arr[i]
      i++
      return element
    }
  }
  return inner
}

// Uncomment the lines below to test your work
const array3 = [1, 2, 3];
const iteratorWithNext = nextIterator(array3);
console.log(iteratorWithNext.next()); // -> should log 1
console.log(iteratorWithNext.next()); // -> should log 2
console.log(iteratorWithNext.next()); // -> should log 3

挑战 3

问题:

编写代码,应用上方的 nextIterator 函数遍历一整个数组,而后求和。

题解:

// CHALLENGE 3

function sumArray(arr) {
  // YOUR CODE HERE
  // use your nextIterator function
  const iteratorWithNext = nextIterator(arr)
  let sum = 0
  let item 
  while(item = iteratorWithNext.next()) {sum += item}
  return sum
}

// Uncomment the lines below to test your work
const array4 = [1, 2, 3, 4];
console.log(sumArray(array4)); // -> should log 10

挑战 4

问题:

创立一个附有 next 办法的迭代器。当调用.next 时,它会返回传入的 set 汇合的每一个元素。

题解:

// CHALLENGE 4

function setIterator(set) {
  // YOUR CODE HERE
  // Solution One:
  // let i = 0
  // const arr = [...set]
  // return {//   next: () => arr[i++]
  // }
  // Solution Two:
  const newSet = set[Symbol.iterator]()
  return {next: () => newSet.next().value}
}

// Uncomment the lines below to test your work
const mySet = new Set('hey');
const iterateSet = setIterator(mySet);
console.log(iterateSet.next()); // -> should log 'h'
console.log(iterateSet.next()); // -> should log 'e'
console.log(iterateSet.next()); // -> should log 'y'

挑战 5

问题:

创立一个附有 next 办法的迭代器。当调用.next 时,它会返回带有两个元素的数组(第一个为下标,第二个为下标对应的数组元素)。

题解:

// CHALLENGE 5

function indexIterator(arr) {
  // YOUR CODE HERE
  let i = 0
  return {next: () => {const element = arr[i]
      const index = i
      i++
      return [index, element]
    }
  }
}

// Uncomment the lines below to test your work
const array5 = ['a', 'b', 'c', 'd'];
const iteratorWithIndex = indexIterator(array5);
console.log(iteratorWithIndex.next()); // -> should log [0, 'a']
console.log(iteratorWithIndex.next()); // -> should log [1, 'b']
console.log(iteratorWithIndex.next()); // -> should log [2, 'c']

挑战 6

问题:

创立一个迭代器。在它的.next 办法被调用时,它会返回一个句子型字符串中的每一个单词。

(提醒:应用正则表达式!)

而后将此操作当成一个办法挂载到构建函数 Words 的原型链上。

(提醒:钻研 Symbol.iterator!)

题解:

// CHALLENGE 6

function Words(string) {this.str = string;}

Words.prototype[Symbol.iterator] = function() {
  // YOUR CODE HERE
  const reg = /\w+/g
  const strArr = this.str.match(reg)
  let index = 0
  return {next: () => 
      (index < strArr.length) ? 
        {done: false, value: strArr[index++] } :
        {done: true, value: undefined}
  }
}

// Uncomment the lines below to test your work
const helloWorld = new Words('Hello World');
for (let word of helloWorld) {console.log(word); } // -> should log 'Hello' and 'World'

挑战 7

问题:

创立一个函数。此函数会遍历传入的数组,返回对应的遍历元素和字符串“was found after index x”拼接而成的字符串后果,其中的 x 是前一个下标。

留神:对于第一个元素,它应该返回“It is the first”。

题解:

// CHALLENGE 7

function valueAndPrevIndex(array){const iteratedArray = array[Symbol.iterator]()
  let index = 0
  return {sentence: () => {if (index == 0) {iteratedArray.next()
        index++
        return `It is the first`
      } else {const result = `${iteratedArray.next().value} was found after index ${index - 1}`
        index++
        return result
      }
    }
  }
}

const returnedSentence = valueAndPrevIndex([4,5,6])
console.log(returnedSentence.sentence());
console.log(returnedSentence.sentence());
console.log(returnedSentence.sentence());

挑战 8

问题:

编写一个函数。它会每三秒钟 console.log 打印“hello there”或“gibberish”,取决于传入函数的值是否为“english”。

请勿应用任何模式的循环且请仅调用 createConversation 一次。

题解:

//CHALLENGE 8

function* createConversation(string) {let output = ''if (string ==='english') {output = 'hello there'} else {output = 'gibberish'}
  yield setInterval(() => {console.log(output)}, 3000)
}

createConversation('english').next();

挑战 9

问题:

应用 async/await 来 console.log 打印一个由名词 noun 和动词 verb 形成的句子,其中非异步函数会接管一个名词 noun,与一个硬编码的动词 verb 拼接,在三秒后返回给异步函数。异步函数接管到数据后,会 console.log 打印相应数据。异步函数仅能调用一次,传入一个名词 noun 见证它的执行吧!

题解:

//CHALLENGE 9
function waitForVerb(noun) {
  return new Promise(resolve => {
    const verb = 'barks'
    setTimeout(() => resolve(`${noun} ${verb}`), 3000)
  })
}

async function f(noun) {const sentence = await waitForVerb(noun)
  console.log(sentence)
}

f("dog")

退出移动版