Getting a surprise image from the collection

I am experiencing an issue with retrieving images from an array. I have an array containing 6 variables that represent the paths to the images. However, when I use console.log at the end, it returns a random variable like sk11, sk15, etc., which do not correspond to the image paths.

.controller('ArCtrl', function($scope) {

  var sk11, sk12, sk13, sk14, sk15, sk16;
  var kockice = ['sk11', 'sk12', 'sk13', 'sk14', 'sk15', 'sk16'];

  var rank = kockice[Math.floor(Math.random() * kockice.length)];

  if(rank === sk11) {
    sk11 = "http://localhost:8100/img/1.jpg";
    rank = sk11;

  } else if(rank === sk12) {
    sk12 = "http://localhost:8100/img/2.jpg";
    rank = sk12;

  } else if(rank === sk13) {
    sk13 = "http://localhost:8100/img/3.jpg";
    rank = sk13;

  } else if(rank === sk14) {
    sk14 = "http://localhost:8100/img/4.jpg";
    rank = sk14;

  } else if(rank === sk15) {
    sk15 = "http://localhost:8100/img/5.jpg";
    rank = sk15;

  } else if(rank === sk16) {
    sk16 = "http://localhost:8100/img/6.jpg";
    rank = sk16;
  }

  console.log(rank); // Returns a random value from the kockice array
  console.log(sk11); // Displays undefined, need to troubleshoot the reason

Answer №1

If you want to randomly assign an image path to the rank variable, you can use the following code:

var images = [ '1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg' ];
var randomImage = images[Math.floor(Math.random() * images.length)];
var rank = 'http://localhost:8100/img/' + randomImage;

Having multiple if statements for each image is unnecessary and inefficient. Using the above code allows for more flexibility without the need to add additional conditions as more images are added to the array.

Answer №2

Update: While my answer addresses the immediate issue, @tdragon's solution may offer a more effective solution.

According to @Parth Trivedi's feedback, remember to enclose your variable in quotes.

For example: if(rank === 'sk11'), if(rank === 'sk12'), and so on.

The reason for this is that you're currently comparing rank with the variable sk11, which lacks a defined value. It's important to compare rank with the string 'sk11'.

Keep in mind that your console.log statement will only display a result if rank matches 'sk11'. Otherwise, it will remain undefined.

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

What is the best way to combine two nearly identical arrays/objects using underscorejs or a similar library?

In the realm of lists, there exists an old list and a new one. The mission at hand is to combine both, even in the presence of newly added key-value pairs. var oldList = [{ id: 1, name: 'Michael', sex: 'male', goodlooking: 1 }, ...

Tips on incorporating a changing variable into a JavaScript Shader

I have successfully created a primitive sphere using THREE.SphereGeometry and applied a displacement shader to give it a bumpy effect. My goal now is to animate the scale of the bumps based on input volume from the microphone. Despite my efforts, I am stru ...

Issues with AngularJS routing functionality are causing it to malfunction

Having Trouble with My Angular Routing Function - Page Loads Without 'home.html' Here is the code I am using: Index.html <html ng-app="App" class="no-js" lang="en" > <head> <script src="https://ajax.googleapis.com/ajax/libs ...

What is the best way to create an array within an object in JavaScript?

Here is the code snippet I'm working with: var Memory ={ personAbove: "someone", words: wordsMem = [] <<<<<this part is not functioning properly } I need help figuring out how to make it function correctly. Specific ...

Retrieve the report information and present it in a HTML data table using a REST API

My understanding of REST API and Javascript is limited, but I now find myself needing to interact with a third-party company's REST API for email reporting purposes. The data can be accessed through a GET method using a URL with a specific TOKEN: {pl ...

What could be causing my div link to redirect to different content instead of the intended destination?

When creating a div to provide information about a course, including the price and a "Take Class" button that links to the purchase page, I encountered an issue where the link extends beyond the intended area. @import url(https://fonts.googleapis.com/cs ...

Show information on a pop-up window using Ajax without having to open a new browser tab

I am currently working on a project that uses the Struts framework. In this project, I need to revamp the UI design. The existing project has a menu tab, and when each menu is clicked, a JSP page opens in a new browser window. However, I want these pages t ...

What could be the reason that data-bs-placement="right" is not functioning as expected?

I am facing an issue with the popover functionality in my project. No matter what value I set for data-bs-placement attribute, it does not display correctly. Can you help me understand why this is happening? <!DOCTYPE html> <html lang="en ...

Enhancing date formatting with Angular and Pikaday

I am currently utilizing the angular-pikaday plugin (available at https://github.com/nverba/angular-pikaday) and encountering an issue with date formatting. My objective is to have a model containing a date string formatted as YYYY-MM-dd. To address this ...

Manipulating a specific element within an ng-repeat in AngularJS without affecting the others

I'm currently working on developing a basic single page application to monitor people's movements. While I've made good progress, I've encountered an issue with the click function in the child elements of each person div. When I try to ...

It is not possible to store data in instances of the same class if they are declared as an array

Recently, I delved into the world of learning java and faced an interesting requirement. My goal is to create instances of my own class in the form of an array. Subsequently, I aim to reference each object using a loop and input data accordingly. The class ...

Can you explain the meanings of <div class="masthead pdng-stn1"> and <div class="phone-box wrap push" id="home"> in more detail?

While working on styling my web pages with CSS and Bootstrap, I came across a few classes like "masthead pdng-stn1" and "phone-box" in the code. Despite searching through the bootstrap.css file and all other CSS files in my folders, I couldn't find a ...

Transformation of Array of Objects to Array of Values using Node.js

I am looking to transform the following: [{ prop1: '100', prop2: false, prop3: null, prop4: 'abc' }, { prop1: '102', prop2: false, prop3: null, prop4: 'def' } ] into this format: [[100,false,null,'abc&ap ...

Using Selenium with JavaScript and Python to simulate key presses

Is there a way to simulate key presses as if typing on a keyboard? I am looking to programmatically click on an input element and then emulate the user typing by pressing keys. I prefer not to use XPath selectors combined with sendkeys or similar methods. ...

Disable the scroll bar on a bootstrap modal

<span class="education"style="font-size:170%;line-height:150%;">&nbsp;Education <br> <small style=" color:gray;font-size:60%;">&nbsp; Blue Ridge University,2012-2014 </small> <br> <sma ...

The inner workings of Virtual DOM in React and Vue disclosed

I am a student experimenting with creating my own Virtual DOM for a college project in JavaScript, keeping it simple without advanced features like props or events found in popular frameworks like React and Vue. I'm curious about code splitting. If I ...

Updating the DOM after making changes with Maquette involves calling the `renderMaquette

In a previous discussion, I expressed my desire to utilize Maquette as a foundational hyperscript language. Consequently, avoiding the use of maquette.projector is essential for me. However, despite successfully appending SVG objects created with Maquette ...

What is the best way to determine the index of the area that was clicked on in chartjs?

I am currently working with a chart that may not have elements at specific indices, but I am interested in determining the index of the area clicked. https://i.sstatic.net/rEMbG.jpg When hovering over an area without an element, the assigned tooltip is d ...

Transforming a collection of tuples into a multi-dimensional MxN numpy array

I am working with a list of tuples, and I want to create a numpy nd.array with specific shape. a=[('1A34', 'RBP', 0.0, 1.0, 0.0, 0.0, 0.0, 0.0), ('1A9N', 'RBP', 0.0456267, 0.0539268, 0.331932, 0.0464031, 4.41336e ...

Create a new variable to activate a function within the parent component in Vue

I want to invoke a function in the parent component from its child component. In my Vue project, I have designed a reusable component that can be used across multiple pages. After the function is executed in this component, I aim to call a specific functi ...