简体   繁体   English

将元素添加到数组并打印元素

[英]Add element to array and print the elements

In arrays.js , define two functions, addElementToBeginningOfArray and destructivelyAddElementToBeginningOfArray .arrays.js ,定义两个函数, addElementToBeginningOfArraydestructivelyAddElementToBeginningOfArray arrays.js Both functions take two parameters, an array and an element to add to the beginning of the array, and both functions should add the element to the beginning of the array and then return the whole array.这两个函数都有两个参数,一个数组和一个添加到数组开头的元素,两个函数都应该将元素添加到数组的开头,然后返回整个数组。 The destructive function, destructivelyAddElementToBeginningOfArray , should alter the original array that's passed in;破坏性函数destructivelyAddElementToBeginningOfArray应该改变传入的原始数组; addElementToBeginningOfArray , on the other hand, should return a new array and not modify the original.另一方面, addElementToBeginningOfArray应该返回一个新数组而不是修改原始数组。

This is my code, but I need to print the array elements:这是我的代码,但我需要打印数组元素:

destructivelyAddElementToBeginningOfArray(arry, elementN){
    arry.unshift(elementN)
    return arry
}

You can print output a few different ways, I would go with console.log personally for homework code, unless you have a brief on how it should print.您可以通过几种不同的方式打印输出,我会亲自使用 console.log 作为作业代码,除非您对如何打印有简要说明。 This is a fairly basic question, that you probably could have found an answer to on your own if you knew where to look :).这是一个相当基本的问题,如果您知道去哪里寻找,您可能可以自己找到答案:)。 I would point you towards MDN for referencing JS, CSS, and HTML.我会指向MDN来引用 JS、CSS 和 HTML。 Hope that helps.希望有帮助。

destructivelyAddElementToBeginningOfArray(array, elementN){
    array.unshift(elementN)
    return array
}
let result = destructivelyAddElementToBegginingOfArray([1, 2, 3], 4);
// pick one
console.log(result);
document.write(result);
alert(result);

Or if you need to illustrate that you are changing inside the function do something like this.或者,如果您需要说明您正在函数内部进行更改,请执行以下操作。

destructivelyAddElementToBeginningOfArray(array, elementN){
    array.unshift(elementN)
    console.log(array);
    return;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM