JavaScript专项算法题(7):Iterators迭代器

简介: Iterators迭代器挑战1问题:A) 创建一个for循环,用于遍历数组,返回数组的所有元素的总和。B) 创建一个函数式迭代器,调用时遍历传入的数组的每一个元素,每次一个元素。题解:123456789101112131415161718192021222324252627282930313233// CHALLENGE 1function sumFunc(arr) { // YOUR CODE HERE let sum = 0 for(let i = 0; i < arr.length; i

Iterators迭代器

挑战1

问题:

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

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

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// CHALLENGE 1
functionsumFunc(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
functionreturnIterator(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被调用时,此迭代器会逐个返回数组内的元素。

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// CHALLENGE 2
functionnextIterator(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函数遍历一整个数组,然后求和。

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// CHALLENGE 3
functionsumArray(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集合的每一个元素。

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// CHALLENGE 4
functionsetIterator(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 = newSet('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时,它会返回带有两个元素的数组(第一个为下标,第二个为下标对应的数组元素)。

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// CHALLENGE 5
functionindexIterator(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!)

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
// CHALLENGE 6
functionWords(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”。

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// CHALLENGE 7
functionvalueAndPrevIndex(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一次。

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
//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见证它的执行吧!

题解:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//CHALLENGE 9
functionwaitForVerb(noun) {
returnnewPromise(resolve => {
const verb = 'barks'
    setTimeout(() => resolve(`${noun}${verb}`), 3000)
  })
}
asyncfunctionf(noun) {
const sentence = await waitForVerb(noun)
console.log(sentence)
}
f("dog")
相关文章
|
9天前
|
JSON 算法 数据可视化
测试专项笔记(一): 通过算法能力接口返回的检测结果完成相关指标的计算(目标检测)
这篇文章是关于如何通过算法接口返回的目标检测结果来计算性能指标的笔记。它涵盖了任务描述、指标分析(包括TP、FP、FN、TN、精准率和召回率),接口处理,数据集处理,以及如何使用实用工具进行文件操作和数据可视化。文章还提供了一些Python代码示例,用于处理图像文件、转换数据格式以及计算目标检测的性能指标。
17 0
测试专项笔记(一): 通过算法能力接口返回的检测结果完成相关指标的计算(目标检测)
|
1月前
|
JavaScript 索引
|
2月前
|
JavaScript 算法 前端开发
JS算法必备之String常用操作方法
这篇文章详细介绍了JavaScript中字符串的基本操作,包括创建字符串、访问特定字符、字符串的拼接、位置查找、大小写转换、模式匹配、以及字符串的迭代和格式化等方法。
JS算法必备之String常用操作方法
|
2月前
|
JavaScript 算法 前端开发
JS算法必备之Array常用操作方法
这篇文章详细介绍了JavaScript中数组的创建、检测、转换、排序、操作方法以及迭代方法等,提供了数组操作的全面指南。
JS算法必备之Array常用操作方法
|
2月前
|
JavaScript 算法 前端开发
"揭秘Vue.js的高效渲染秘诀:深度解析Diff算法如何让前端开发快人一步"
【8月更文挑战第20天】Vue.js是一款备受欢迎的前端框架,以其声明式的响应式数据绑定和组件化开发著称。在Vue中,Diff算法是核心之一,它高效计算虚拟DOM更新时所需的最小实际DOM变更,确保界面快速准确更新。算法通过比较新旧虚拟DOM树的同层级节点,递归检查子节点,并利用`key`属性优化列表更新。虽然存在局限性,如难以处理跨层级节点移动,但Diff算法仍是Vue高效更新机制的关键,帮助开发者构建高性能Web应用。
62 1
|
3月前
|
算法 JavaScript
JS 【详解】树的遍历(含深度优先遍历和广度优先遍历的算法实现)
JS 【详解】树的遍历(含深度优先遍历和广度优先遍历的算法实现)
62 0
JS 【详解】树的遍历(含深度优先遍历和广度优先遍历的算法实现)
|
3月前
|
存储 JavaScript 前端开发
JavaScript编码之路【ES6新特性之 Symbol 、Set 、Map、迭代器、生成器】(二)
JavaScript编码之路【ES6新特性之 Symbol 、Set 、Map、迭代器、生成器】(二)
47 1
|
3月前
|
算法 JavaScript
JS 【详解】二叉树(含二叉树的前、中、后序遍历技巧和算法实现)
JS 【详解】二叉树(含二叉树的前、中、后序遍历技巧和算法实现)
42 0
|
3月前
|
算法 JavaScript
JS 【算法】二分查找
JS 【算法】二分查找
31 0
|
3月前
|
JavaScript 索引
JS的迭代器是啥?精读JS迭代器
JS的迭代器是啥?精读JS迭代器
22 0