需要创建一个函数,该函数从数组中获取一个值,将其存储,然后仅使用 .pop 和 .push

我必须为我正在学习的 JS 课程解决这个练习:“创建一个以两个数组作为参数的函数,从第一个数组中取出最后一个值,然后将其放入第二个数组中。” 我希望使用的命令是 .push 和 .pop,我不能使用 concat 或这两个以外的任何命令。


本课程向您展示了该函数应该做什么的示例:


let anArray = [1, 2];

let anotherArray = [3, 4];


move(anArray, anotherArray);


anArray //should be [1]

otroArray //should be [3,4,2]

这是我到目前为止所写的:


function move (parameter,parameter2){

 var anArray = [1,2];

 var anotherArray = [3,4];

 var storage = anArray.pop();

 anotherArray.push(storage);

}

我真的很困惑为什么我不能让它工作。我对 JS 真的很陌生,非常感谢一些帮助。



慕运维8079593
浏览 57回答 2
2回答

米琪卡哇伊

您没有使用函数参数,而是定义了新变量。这会起作用:function move(parameter, parameter2) {  var storage = parameter.pop();  parameter2.push(storage);}let anArray = [1, 2];let anotherArray = [3, 4];move(anArray, anotherArray)console.log(anArray)console.log(anotherArray)

动漫人物

因为在move你定义的函数anArray中anotherArray。外部数组的范围与内部定义的变量的范围不同。实际上,移动发生在方法内部定义的数组中。由于您已经使用相同的名称定义了它们,因此会造成混淆。请参阅下文,了解您所做的实际工作但不在传递的参数上的实现function move(parameter, parameter2) {  var anArray = [1, 2];  var anotherArray = [3, 4];  var storage = anArray.pop();  anotherArray.push(storage);  console.log(anArray)  console.log(anotherArray)}move([],[])因此,为了使您的函数在您传递的输入参数上工作,您实际上可以进行如下更改function move(parameter, parameter2) {  const storage = parameter.pop();  parameter2.push(storage);}let anArray = [1, 2];let anotherArray = [3, 4];move(anArray, anotherArray)console.log(anArray)console.log(anotherArray)希望这可以帮助。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript