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
This commit is contained in:
parent
ad51aa4fb9
commit
d9bba74979
55
5.5Iterables/t.js
Normal file
55
5.5Iterables/t.js
Normal file
@ -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);
|
Loading…
Reference in New Issue
Block a user