[英]Appending a variable to an array without changing it
I'm currently working on a pre-bootcamp course and haven't been able to find help online in order to solve a problem that has me a bit confused. 我目前正在进行一个训练前课程,并且无法在线寻求帮助以解决让我有点困惑的问题。
I understand when we use JavaScript we have push(), pop(), shift() and unshift() methods we can use in order to add/remove from an array. 我知道当我们使用JavaScript时,我们可以使用push(),pop(),shift()和unshift()方法来添加/删除数组。 The problem I'm running into is the test question ask:
我遇到的问题是测试问题:
1) Arrays appendKitten(name) appends a kitten to the kittens array and returns a new array,
leaving the kittens array unchanged:
I've been confused for nearly a day in solving this problem. 我已经困惑了近一天来解决这个问题。 I get when we do want to change the array we'll use one of the methods.
当我们想要更改数组时,我会使用其中一种方法。 For example when we append it'll be:
例如,当我们追加它时,它将是:
var kittens = ["Milo", "Otis", "Garfield"]
function destructivelyAppendKitten(name){
kittens.push(name)
return kittens
}
Which will push a new kitten(name) into the array. 这将把一只新的小猫(名字)推入阵列。 Now in order to solve the previous test I've written:
现在为了解决以前的测试,我写了:
function appendKitten(name){
var newArray = []
var kittens = kittens.concat(newArray);
kittens.push(name)
return kittens
}
but continue to receive the same error. 但继续收到同样的错误。 Is there something I'm missing?
有什么我想念的吗?
My thought process in solving this question: 我在解决这个问题时的思考过程:
1- We are calling a function names appendKittens with a single argument -> name. 1-我们使用单个参数 - > name调用函数名称appendKittens。
2- We are pushing data from the kitten variable into a local kitten instance in order to have the same array. 2-我们正在将数据从小猫变量推送到本地小猫实例,以便拥有相同的数组。
3- We push whatever name passes in the parameter into the new array. 3-我们将参数中传递的任何名称都推送到新数组中。
4- Return the new array which had the push() performed leaving global kitten untouched. 4-返回执行push()的新阵列,使全局小猫不受影响。
Is my thinking process off? 我的思维过程了吗? any ideas to where I'm off?
我离开的地方有什么想法吗? All those who help.
所有帮助的人。 Thank you, really do appreciate it.
谢谢,真的很感激。
function appendKitten(name){
var newArray = kittens.slice();
// or ES6 way
// var newArray = [...kittens];
newArray.push(name)
return newArray
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.