简体   繁体   English

以数组为参数的JavaScript函数

[英]JavaScript function that takes an array as a parameter

I am trying to create a JavaScript function that takes an array as a parameter and returns the first item in the array. 我正在尝试创建一个JavaScript函数,该函数将数组作为参数并返回数组中的第一项。 This should work for an array of any size. 这适用于任何大小的数组。 Here is what I have so far, it appears to work just fine in the console but my instructor says there's a better way to do this: 这是我到目前为止所拥有的,在控制台中似乎可以正常工作,但是我的教练说有更好的方法可以做到这一点:

var array = [];

function numbaOne(array) {
    for (var i = 0; i < array.length; i++) {
        console.log(array[0])
    };
}

Any help would be appreciated. 任何帮助,将不胜感激。 I've read about data structures and arrays but can't figure out how to simplify or make this better. 我已经读过有关数据结构和数组的信息,但无法弄清楚如何简化或改进它。

What you are doing is looping over the array and printing out the first item each time. 您正在做的是遍历数组并每次打印出第一项。 You just want: 您只想要:

var array = [...];

function numbaOne(array) {
    console.log(array[0]); // Print out the first value of the array
    return array[0]; // Return the first value of the array
}

There is one edge case here. 这里有一个极端的情况。 If the array is empty, then the function will fail because array[0] will be undefined . 如果数组为空,则该函数将失败,因为array[0]将是undefined So, a more complete version might be: 因此,一个更完整的版本可能是:

var array = [...];

function numbaOne(array) {
    if(array.length > 0) { // Check if there is anything in the array
        console.log(array[0]);
        return array[0];
    } else { // If there isn't, let's return something "bad"
        console.log("The array is empty!");
        return undefined;
    }
}

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

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