【问题标题】:Need to create a function that takes a value from an array, stores it, then places it in a second array using only .pop and .push需要创建一个函数,该函数从数组中获取一个值,将其存储,然后仅使用 .pop 和 .push 将其放置在第二个数组中
【发布时间】:2020-07-01 16:05:36
【问题描述】:

我必须为我正在学习的 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 新手,非常感谢一些帮助。

提前致谢,

路易斯。

【问题讨论】:

    标签: javascript arrays function


    【解决方案1】:

    您没有使用函数参数,而是定义了新变量。 这会起作用:

    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)

    【讨论】:

    • 非常感谢!我已经为此苦苦挣扎了两天,已经添加了不需要的额外内容。非常感谢你,你救了我。
    • 很高兴,我可以帮助你!
    • @LuisArgüelles 你能接受答案吗?会很亲切。祝你好运。
    • 之前它说现在这样做还为时过早,再次感谢您!
    【解决方案2】:

    因为在函数move 中您又定义了anArrayanotherArray。外部数组的范围与内部定义的变量的范围不同。 实际上,移动发生在方法内部定义的数组中。由于您使用相同的名称定义了它们,因此会造成混淆。

    请参阅下面的实现,了解您所做的实际工作,但不是在传递的参数上

    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)

    希望这会有所帮助。

    【讨论】:

    • 非常感谢!我已经解决了,但这也有效!我通过阅读您的代码和其他人的代码学到了很多东西。我真的很感激。
    猜你喜欢
    • 2018-05-01
    • 1970-01-01
    • 2022-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-02
    • 1970-01-01
    • 2021-06-14
    相关资源
    最近更新 更多