Struggling with a beginner arrays exercise, looking for help

Currently, I am delving into the realm of JavaScript and encountering some hurdles with arrays in this programming language. My task at hand is to create a class named TV Show that includes attributes such as title, thematic element, and an array of actors. Subsequently, I am required to develop a function that randomly designates one actor from the array as the "favorite."

Upon completing this task, I find myself left with an empty array.

Below is the code snippet:

class TVShow {
    constructor (title, thematic, principalActors){
        var arrayActors = new Array();
        this.title=title;
        this.thematic=thematic;
        principalActors=[];
    
        this.generateFavActor = function(){
            var long = principalActors.lenght;
            let calc = Math.floor(Math.random()*(long));
            arrayActors = principalActors[calc];
        }
        console.log(arrayActors);
    }
}
var show01= new TVShow("The Revolution", "Accion",["Hello","Hello2"]);
show01.generateFavActor();

var show02 = new TVShow("Peaky Blinders", "Drama",["Hello","Hello2", "Hello3"] );
show02.generateFavActor();

var show03 = new TVShow ("Stranger Things", "Accion", ["Hello","Hello2", "Hello3", "Hello4"]); 
show03.generateFavActor();

Thank you for your assistance!

Answer №1

Can you achieve this using Destructuring assignment?

class TVShow
  {
  constructor (title, thematic, principalActors)
    {
    this.title    = title
    this.thematic = thematic
    this.actors   = [...principalActors]
    }
  generateFavActor()
    {
    console.log( this.actors[ Math.floor(Math.random()*this.actors.length ) ])
    }
  }
var show01 = new TVShow('The Revolution',  'Accion', ['Hello','Hello2'])
  , show02 = new TVShow('Peaky Blinders',  'Drama',  ['Hello','Hello2', 'Hello3'] )
  , show03 = new TVShow('Stranger Things', 'Accion', ['Hello','Hello2', 'Hello3', 'Hello4'])
  ;
show01.generateFavActor()
show02.generateFavActor()
show03.generateFavActor()

Answer №2

Here is a possible solution for what you're looking to achieve:

class Show {
    constructor (name, genre, actors){        
        this.name = name;
        this.genre = genre;
        this.actorList = actors;       

        this.selectFavoriteActor = function(){
            var totalActors = actors.length;
            let randomIndex = Math.floor(Math.random() * (totalActors));
            return actors[randomIndex];
        }       
        this.favoriteActor = this.selectFavoriteActor();
    }
}

var show1 = new Show("Breaking Bad", "Crime", ["Bryan Cranston", "Aaron Paul"]);
var favoriteActor1 = show1.favoriteActor;

var show2 = new Show("Friends", "Comedy", ["Jennifer Aniston", "Courteney Cox", "Lisa Kudrow"]);
var favoriteActor2 = show2.favoriteActor;

var show3 = new Show ("Game of Thrones", "Fantasy", ["Emilia Clarke", "Kit Harington", "Peter Dinklage"]); 
var favoriteActor3 = show3.favoriteActor;

console.log(favoriteActor1);
console.log(favoriteActor2);
console.log(favoriteActor3);

Answer №3

First, ensure to correct the reference to principalActors.length, not principalActors.lenght.
Secondly, avoid initializing principalActors as an empty array.
Next, simply include a console.log statement inside the function...
It will provide the correct answer...currently displaying the value assigned to an empty array var arrayActors = new Array()
Hopefully this is Helpful :-)
Also, I believe arrayActors does not need to be an array.

class TVShow {
    constructor (title, thematic, principalActors){
        var arrayActors = new Array();
        this.title=title;
        this.thematic=thematic;
        
    
        this.generateFavActor = function(){
            var long = principalActors.length;
            let calc = Math.floor(Math.random()*(long));
           arrayActors = principalActors[calc];
           console.log(arrayActors);
        }
        
    }
}
var show01= new TVShow("The Revolution", "Action",["Hello","Hello2"]);
show01.generateFavActor();

var show02 = new TVShow("Peaky Blinders", "Drama",["Hello","Hello2", "Hello3"] );
show02.generateFavActor();

var show03 = new TVShow ("Stranger Things", "Action", ["Hello","Hello2", "Hello3", "Hello4"]); 
show03.generateFavActor();

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Failure to Present Outcome on Screen

Seeking assistance! I attempted to create a mini loan eligibility web app using JavaScript, but encountered an issue where the displayed result did not match the expected outcome upon clicking the eligibility button. Here is the HTML and JavaScript Code I ...

Child component not reflecting changes in Vue array prop

One issue I encountered is with a model from a backend where the property that typically contains an array of elements can be nullable. To handle this, I initialize it to an empty array. However, this seems to disrupt my ability to update the array in the ...

Error message: "Unable to access D3 data when trying to select nested

Working with JSON data in D3 is proving to be a challenge for me. The file seems to be properly read, as indicated by its appearance when I use console.log, and it appears to be correctly formatted based on the examples I have come across. However, when I ...

How to automatically terminate a program after fgets() reads a specified ending line from standard input redirection

I am facing an issue with a program that reads lines of a file. The program is supposed to stop reading lines once it encounters the line *** END *** and checks for the condition to end using char str[100]; while(fgets(str,100,stdin) != NULL & ...

typescript library experiencing issues with invalid regex flags in javascript nodes

I am facing an issue while attempting to import a plain JavaScript module into a Node application written in TypeScript. The error below is being thrown by one of the codes in the JavaScript module. b = s.matchAll(/<FILE_INCLUDE [^>]+>/gid); Synta ...

Generating a String Array from an Integer Array in C

I'm currently working on converting an array of integers to an array of strings in C. The code I've written so far is: int args[] = {1, 3000}; char *str_args[15]; int i = 0; for(i; i <= ((sizeof(args) / sizeof(args[0]))); i++) { char ...

Guide to utilizing a variable inside a string within an array in PHP

Here is a function that I need to repeat multiple times while changing the array values: register_field_group(array ( 'id' => 'acf_page-options-cat-work', 'title' => 'Featured Posts', 'fields& ...

Anomaly observed in the deconstruction of Material UI table components

Utilizing the table component from the Material UI react components library, I encountered a need to incorporate custom behavior into the TableRow. To achieve this, my approach involved breaking down the table and planning to encapsulate it within my own ...

Error: The name property is not defined and cannot be read in the Constructor.render function

Having trouble building a contact form and encountering an error when trying to access the values. I've checked for bugs in the console multiple times, but it seems like something is missing. Can anyone provide assistance? var fieldValues = { ...

What is the best way to utilize the ajax factory method in order to establish a $scoped variable?

One issue I frequently encounter in my controllers is a repetitive piece of code: // Get first product from list Product.get_details( id ) .success(function ( data ) { // Setup product details $scope.active_product = data; }); To avoid this ...

Choose an option from the dropdown menu when clicking on the radio button

My issue involves a drop-down menu along with two radio buttons, each with two values: jQuery('input[type=radio][name=radio_type]').change(function(e) { var value = jQuery(e.target.value); jQuery('select[name="optType"] option:selecte ...

Discovering the Sum of K with Node JS Value Mapping

Imagine you have a list of numbers like this: const arr = [{ key1: 10 }, { key2: 5 }, { key3: 7 }, { key4: 17 }];, and also a number k which is represented by const k = 17;. Your task is to determine if any two numbers from the list can be added up to equa ...

What causes the string to be treated as an object in React Native?

I am fetching a string value through an API and I need to display it in the View. However, the string value is coming as a Promise. How can I handle this? "Invariant Violation: Objects are not valid as a React child (found: object with keys {_40, _65 ...

There seems to be an issue with the import class for React PropTypes. The prop

I have multiple oversized items that are utilized in numerous components, so I created a PropTypes file for each item. For example: PropTypes/PropLargeObject.js This file contains: import PropTypes from "prop-types"; const PropLargeObject = Prop ...

Adjusting the Materui LinearProgressWithLabel progress value to reflect a custom value

Is it possible to update the progress value of Material UI's LinearProgressWithLabel component with a custom value instead of the default one? I am trying to achieve this by obtaining my desired value from the upload progress in the Axios.post method, ...

How to retrieve a nested element from a multidimensional array using Angular

Need help with Angular - I'm working on a json file containing an array called people[], which in turn has an array named phones[] I aim to extract and display: people[index].phones[index].phonenumber (assuming people.personid = x and people.phones ...

Adaptive video player for complete YouTube experience

Is there a way to incorporate a YouTube video as the background of a div, similar to how it is done on this site, using a <video> tag and ensuring that the video "covers" the entire div without any empty spaces while maintaining its original ratio? ...

Convert bitmap images to byte arrays and then decode them back to their original format without

I'm having trouble converting bitmap to byte array without using bitmap.compress. Whenever I try to decode the array, BitmapFactory.decodeByteArray always returns NULL. Here is the encode method: public byte[] ConvertToByteArray(Bitmap image) { ...

Can a website accurately identify my operating system and browser version even if my browser settings have been altered?

When using selenium to browse a website, I have modified the useragent, platform, and oscpu properties of the navigator object in my Firefox browser. Will the website be able to detect my actual operating system and browser version? ...

Executing Code Upon Module Load and Presenting It as Middleware

I am currently delving into the intricacies of how exporting and importing modules function in Nodejs. One of my tasks involves using a specific file to seed a mongodb database. Surprisingly, this file operates flawlessly and delivers the desired results ...