我正在寻找抓住数组(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});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句