赞
踩
ES2015 即es6新增方法
具体使用情况:
const arr = [1, 2, 3, 4, 5];
const newArr1 = arr.copyWithin(1, 3, 4);
console.log(newArr1);// [1, 4, 3, 4, 5]
const arr = [1, 2, 3, 4, 5];
const newArr2 = arr.copyWithin(0, 2, 5);
console.log(newArr2);// [3, 4, 5, 4, 5]
const arr = [1, 2, 3, 4, 5];
const newArr3 = arr.copyWithin(10, 2, 4);
console.log(newArr3);// [1, 2, 3, 4, 5]
const arr = [1, 2, 3, 4, 5];
const newArr1 = arr.copyWithin(3, 1, 3);
console.log(newArr1);// [1, 2, 3, 2, 3]
const arr = [1, 2, 3, 4, 5];
const newArr1 = arr.copyWithin(3, -3, -1); // 3 2 4
console.log(newArr1);// [1, 2, 3, 3, 4]
const arr = [1, 2, 3, 4, 5];
const newArr1 = arr.copyWithin(3);
console.log(newArr1);// [1, 2, 3, 1, 2]
const arr = [1, 2, 3, 4, 5];
const newArr1 = arr.copyWithin(3);
console.log(arr === newArr1); // true
/**
* @param
* target:必填
* start:非必填
* end:非必填
*/
Array.prototype.myCopyWithin = function(target) {
if(this === null) {
throw new TypeError('ths is null or not defined');
}
// 把当前this用Object包装一下,变成引用值
var obj = Object(this),
len = obj.length >>> 0, // 右位移,保证他是正整数
start = arguments[1],
end = arguments[2],
count = 0,
dir = 1;
target = target >> 0; // 保证他是正整数
target = target < 0 ?
Math.max(len + target, 0):
Math.min(target, len);
start = start ? start >> 0 : 0;
start = start < 0 ?
Math.max(len + start, 0):
Math.min(start, len);
end = end ? end >> 0 : len;
end = end < 0 ?
Math.max(len + end, 0):
Math.min(end, len);
count = Math.min(end - start, len - target);
if(start < target && target < (start + count)) {
dir = -1;
start += count - 1;
target += count - 1;
}
while(count > 0) {
if(start in obj) {
obj[target] = obj[start];
}else {
delete obj[target];
}
start += dir;
target += dir;
count --;
}
return obj;
}
遍历:
一次性对数组中每一个元素进行查询和处理
迭代:
我们希望遍历的过程是可控的(遍历的过程是可停止,可继续的),手动控制遍历流程。
产品迭代: 人为控制的产品升级与扩展
生成器:函数
迭代器:是生成器函数执行后返回的一个带有next方法的对象
生成器对迭代的控制是由yield关键字来执行的
const arr = [1, 2, 3];
function * gen(arr) {
for(var i = 0; i < arr.length; i++) {
yield arr[i];
}
return '结束';
}
const iterator = gen(arr);
console.log(iterator.next());//{value: 1, done: false}
console.log(iterator.next());//{value: 2, done: false}
console.log(iterator.next());//{value: 3, done: false}
console.log(iterator.next());//{value: '结束', done: true}
function gen(arr) {
var nextIdx = 0;
return {
next: function() {
return nextIdx < arr.length ?
{value: arr[nextIdx ++], done: false} :
{value: arr[nextIdx ++], done: true};
}
}
}
const iterator = gen(arr);
console.log(iterator.next());
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。