Introduce
入职之后发现有每周答题唉, 一开始紧张的一批,后来发现很有趣唉,哈哈哈哈,我果然没有菜到不可救药
Question
已知数组 arr = [1, 2, 3, 4, 5]
给定索引值,对应数组项向前移动一位
给定索引值,对应数组项移动到最前面
给定索引值,对应数组项移动到最后面
实现任意两个数组项位置互换
Answer
-
别人写的,贼简洁,非常棒。
// 向前一位 const moveForward = (arr, index) => { return exchange(arr, index, index - 1); } // 最前 const moveFirst = (arr, index) => { arr.unshift(arr.splice(index, 1)[0]); return arr; } // 最后 const moveLast = (arr, index) => { arr.push(arr.splice(index, 1)[0]); return arr; } // 交换 const exchange = (arr, index1, index2) => { arr[index1] = arr.splice(index2, 1, arr[index1])[0]; return arr; }
-
我写的,想的是通过es6的简单语法的。
// 已知数组 arr = [1, 2, 3, 4, 5] let arr = [1, 2, 3, 4, 5]; let arrLen = arr.length; // 抛错 let throwWrong = (index, leftIndex, rightIndex) => { if (index < leftIndex || index > rightIndex) { throw new Error('索引越界') } } // 无意义 let undo = (index, compIndex) => { if (index === compIndex) { console.log("无意义的移动"); } } // 给定索引值,对应数组项向前移动一位 let forward = (arr, index) => { throwWrong(index, 1, arrLen - 1); changePos(arr, index, index - 1); return arr; } // 给定索引值,对应数组项移动到最前面 let goToFirst = (arr, index) => { throwWrong(index, 0, arrLen - 1); undo(index, 0); changePos(arr, 0, index); return arr; } // 给定索引值,对应数组项移动到最后面 let goToLast = (arr, index) => { throwWrong(index, 0, arrLen - 1); undo(index, arrLen - 1); changePos(arr, index, arrLen - 1); return arr; } // 实现任意两个数组项位置互换 let changePos = (arr, onePos, anotherPos) => { if (onePos < 0 || anotherPos >= arrLen) { throw new Error('索引越界'); } [arr[onePos], arr[anotherPos]] = [arr[anotherPos], arr[onePos]] return arr; }
Author
{
"author" : "jontyy",
"email":"jontyy@163.com"
}