我必须创建一个函数,它返回传入的数组的最后一个元素

时间:2016-03-31 22:11:04

标签: javascript arrays

我迷失了如何在函数中使用数组。这是我的,但它不是一个功能,所以它是不正确的?

var theLastOne = [1,2,3,4,5,'purple'];
var last_element = theLastOne[theLastOne.length - 1];
    console.log(last_element)

这是确切的问题。创建一个名为theLastOne的函数,它返回传入的数组的最后一个元素。提示:这应该适用于任何大小的数组。

2 个答案:

答案 0 :(得分:1)

编写函数时,请考虑输入和输出。您希望函数接受数组作为参数,返回最后一个元素

这样的事情

function theLastOne(array) {
  var lastElement = /* somehow get it from the passed array parameter */;

  return lastElement;
}

你已经知道如何以某种方式从传递的数组中获取它",你在你的例子中有它:)

答案 1 :(得分:0)

像其他人说的那样,你只需要重新格式化,但你可以这样做:与其他人一样,只是解释一下。

// here is your array
var arrayExample = [3,4,5,'hello','whatever']

// here is your function - see that 'arr', that is the array you will 
// pass in. The reference your function will use to access 
// the passed in array. It is an 'argument'
function theLastOne(arr) {
   return arr[arr.length - 1];
}

    // call it like this
    console.log(theLastOne(arrayExample))

   // or like this
    console.log(theLastOne([3,4,5,'hello','whatever']))

要么明确地传入一个数组(第二个例子)..它就在那里,当你传入它时就在那里。

OR

作为参考传递它,第一个例子。

注意:我正在使用console.log,因此您可以在开发人员控制台中查看输出。在实际代码中,您不会包含它。你也可以警告"而不是使用console.log