From d9bba749797b96498d619312f79f4e6bdc4d2b6a Mon Sep 17 00:00:00 2001 From: mhrooz Date: Tue, 18 Jun 2024 00:11:16 +0200 Subject: [PATCH] Iterables: add a [Symbol.Iterable] to make the object iterable so that the object can use for of loop the [Symbol.Iterable] is a function, it should return a object includesdone and value Array.from method can return Array.from a arraylike object and iterable object string can be used in array.from as well --- 5.5Iterables/t.js | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 55 insertions(+) create mode 100644 5.5Iterables/t.js diff --git a/5.5Iterables/t.js b/5.5Iterables/t.js new file mode 100644 index 0000000..9c8608f --- /dev/null +++ b/5.5Iterables/t.js @@ -0,0 +1,55 @@ +let range = { + from: 1, + to: 5 +} + +range[Symbol.iterator] = function(){ + + return { + current: this.from, + last: this.to, + + next(){ + if(this.current <= this.last){ + return {done: false, value: this.current++}; + } else { + return {done: true}; + } + } + } +}; + + +for(let num of range){ + console.log(num); +} + +for(let ch of "tests"){ + console.log(ch) +} + +let arrayLike = { + 0: "Hello", + 1: "World", + length: 2 +}; + +// Array.from +let arr = Array.from(arrayLike); +console.log(arr.pop()); // World +arr = Array.from(range); +console.log(arr); //1, 2, 3, 4, 5 +arr = Array.from(range, num => num * num); +console.log(arr); //1, 4, 9, 16, 25 + +let s = "split"; +let split_s = s.split(''); +let arr_s = Array.from(s); +console.log(split_s); +console.log(split_s[0]); +console.log(split_s[1]); +console.log(split_s.length); +console.log(arr_s); +console.log(arr_s[0]); +console.log(arr_s[1]); +console.log(arr_s.length);