简体   繁体   中英

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. 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 . 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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