我正在寻找数组(sourceArr)中的前两个位置,并将它们分配给变量(此处代码中的p&k)。使用rest运算符可以在另一个数组结果中给我剩下的数组(arr19)。这段代码似乎可以很好地抓住其余部分。但是,由于我尝试将初始位置作为变量,因此出现“ Uncaught ReferenceError:p未定义”。
关于我在做什么错的任何提示!我认为const [p,k,... arr19] = listMe会定义p和k ???
const sourceArr = [1,2,3,4,5,6,7,8,9,10]
function reassignFirstTwo(listMe) {
const [ p, k, ...arr19] = listMe // the p & k variables are grabbed, followed by the REST dots (...) to grab the remaining array elements.
return (p)
return (k)
return arr19
}
const arr19 = reassignFirstTwo(sourceArr)
console.log(arr19) // This gives the resulting array with the elements removed
console.log(sourceArr) // This gives the original array
console.log(p)
console.log(k)
函数中的第一个return
仅返回p
的1
变量值,并在退出函数时跳过接下来的两个返回。
p
和k
的作用范围是功能reassignFirstTwo
,因此您不能在该功能之外访问它。您尝试全局访问的内容,因此您会获得Uncaught ReferenceError: p is not defined
。
您可以通过reassignFirstTwo
函数将这三个变量作为对象返回,然后使用对象分解技术对其进行解构以获取变量arr19, p, k
(新变量):
const sourceArr = [1,2,3,4,5,6,7,8,9,10]
function reassignFirstTwo(listMe) {
const [ p, k, ...arr19] = listMe;
return {p, k, arr19}
}
const { arr19, p, k } = reassignFirstTwo(sourceArr)
console.log({arr19, sourceArr, p, k});