需求:调换数组内元素的位置,不做替换。
在Es6中有一个copyWithin的方法,这个方法不满足需求,它是将指定位置的成员复制到其他位置,会覆盖原有成员。然后返回当前数组,会修改原数组。
Array.prototype.copyWithin(target, start = 0, end = this.length)
它接受三个参数。
target(必需):从该位置开始替换数据。如果为负值,表示倒数。start(可选):从该位置开始读取数据,默认为 0。如果为负值,表示从末尾开始计算。end(可选):到该位置前停止读取数据,默认等于数组长度。如果为负值,表示从末尾开始计算。
这三个参数都应该是数值,如果不是,会自动转为数值。
[1, 2, 3, 4, 5].copyWithin(0, 3)// [4, 5, 3, 4, 5]
下面是新写的一个方法arrayReplace,它有两个参数第一个参数start被调换位置的下标,第二参数byindex调换位置的下标它是个参数集合可以传递多个下标。
list.arrayReplace(0, 4, 5, 6)
byindex传递的是4,5,6,start传递的是0,那么start则从0开始读取它的结束值是byindex的长度,start是0,1,2。
例:
原数组:
替换后:
注意:
1. 被调换的元素,和调换的元素不能同时出现。
2.byindex参数如果传递多个下表,则下表需要连贯传入。
3. arrayReplace方法不改变原数组。
例:
1. 同时出现的元素
list.arrayReplace(2, 4, 5, 6)
start传递的是2,那么从2开始读取,byindex传递了三个参数,start读取结果则是2,3,4。byindex传递的是4,5,6下标4在两个参数读取结果中同时出现。
2. byindex传递多个不连贯的下标
list.arrayReplace(2, 6, 8, 9)
代码:
Array.prototype._arrayReplace = function (start, ...byindex) {if (!Array.isArray(this)) throw Error(`${this}._arrayReplace is not function`)const ARRAY = JSON.parse(JSON.stringify(this))const l = byindex.lengthconst min = Math.min(...byindex)const max = Math.max(...byindex)let end = startfor (let i = 0; i < l; i++) {end += 1}for (let l = byindex[byindex.length - 1]; l >= min; l--) {if (!byindex.includes(l)) {throw Error(`byindex:传入下标不连贯,缺少下表${l}`)}}if (start < 0 || min < 0) throw Error('start:或byindex:传入下表过小')if (start > ARRAY.length - 1 || max > ARRAY.length - 1) throw Error('start:或byindex:传入下表过大')if (byindex.includes(end - 1)) throw Error(`byindex:下表与start:下表重合,重合下表"${end - 1}"`)const StartWill = ARRAY.slice(start, end)const ByWill = ARRAY.slice(min, max + 1)ARRAY.splice(start, l, ...ByWill)ARRAY.splice(min, l, ...StartWill)return ARRAY}