JavaScript's Extended Array feature is not functioning as anticipated, and no error message is being displayed

Hello, I am currently delving into JavaScript for a project I'm working on and have encountered a question regarding the following snippet of code.

function randomArr(){};
randomArr.prototype = new Array(); 
randomArr.prototype.getRandomValue = function(){
    var index = Math.floor(this.length * Math.random()); // returns a value between 0 and 1  
    return this[index];
}

var arr = new randomArr('seoul', 'tokyo', 'beijing');
console.log(arr.getRandomValue());

After running this code in the web browser, the output displayed is simply 'undefined'.

Answer №1

In my opinion, it's more effective to incorporate that function into the Array type:

Array.prototype.selectRandomValue = function(){
    var index = Math.floor(this.length * Math.random()); // produces a random index from 0 to 1  
    return this[index];
}

Array cities = new Array('New York', 'London', 'Paris');
console.log(cities.selectRandomValue());

Check out this insightful explanation:

As per the guidance provided in that article, it is recommended to define arrays like this:

var cities = ['New York', 'London', 'Paris'];
console.log(cities.selectRandomValue());

I trust this information is beneficial!

Answer №2

ES6 classes offer a significant benefit in that they can subclass unique classes like arrays. Attempting to subclass arrays in older versions of Javascript can be done, but the process is not worth explaining here.

Another issue arises when using a subpar pattern of subclassing in pre-ES6 Javascript. In this scenario, the base class is instantiated, and an instance of the base class is added to the new class's prototype chain without proper linkage. TypeScript utilizes a similar method internally, but with flawed assumptions. In the provided code, the Array constructor is already executed before the list of cities is added, resulting in a failure even if subclassing arrays in this manner was possible.

The presented code showcases the contemporary approach to achieving this task. By addressing the concerns raised in Eleazar's link, the constructor's arguments are not directly passed to the Array base constructor. Instead, the base constructor generates an empty array, followed by adding the values into it.

class randomArr extends Array{
    constructor(..._items){
        super()
        _items.forEach(_=>this.push(_))
    }
    getRandomValue(){
        const index=Math.floor(this.length*Math.random())
        return this[index]
    }
}

let arr=new randomArr('seoul', 'tokyo', 'beijing')
console.log(arr.getRandomValue())

Contrary to Eleazer's recommendation, it is advisable to refrain from adding named properties to core prototypes. Symbol properties are a more suitable option for this purpose. The following demonstrates how to implement this:

const getRandomValue=Symbol()
Reflect.defineProperty(
    Array.prototype,
    getRandomValue,
    {
        value(){
            const index=Math.floor(this.length*Math.random())
            return this[index]
        }
    }
)

let arr=['seoul', 'tokyo', 'beijing']
console.log(arr[getRandomValue]())

The use of symbols ensures that there are no conflicts with other libraries extending the Array prototype.

Answer №3

This technique utilizes the prototype chain to avoid directly adding methods to Array.prototype.

function customArray() {                                             
Array.call(this);                                                      
  for (x in arguments) {                                 
  this.push(arguments[x]);                                           
  }                                                                         
}                                                         

customArray.prototype = Object.create(Array.prototype); 
customArray.prototype.constructor = customArray; 

customArray.prototype.getUniqueValue = function(){                          
var index = Math.floor(this.length * Math.random()); // generates a random index     
return this[index];                                         
}                                                                         

var myArray = new customArray('paris', 'london', 'madrid');      
alert(myArray.splice(1,1));  // functioning as intended    
alert(myArray.getUniqueValue()); // executing correctly

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

Why is it that when I refresh the page in Angular, my logged-in user is not being recognized? What could be causing this

I am developing a Single Page Application using the combination of Angular JS and Node JS. In my HTML file, I have defined two divs and based on certain conditions, I want to display one of them using ng-if. However, I noticed that the model value used in ...

Prevent the automatic inflation of bubbles on the D3 World Map

Currently, I am developing a D3 world map with a zoom feature that allows users to zoom in up to the boundary level of any country or county by clicking on it. I have successfully added bubbles that point to various counties in Kenya, and these bubbles en ...

How to pass a single value using onClick event without relying on form submission

I prefer to pass a single value instead of multiple putPriority fetch calls. This value will not be inputted by the user directly, but rather passed through an onClick event. For example, I want the onClick to send a specific number to "status" in the fe ...

Is it no longer possible to use v-for to iterate over translations in Nuxt 3 and @nuxtjs/i18n?

Imagine having an Array stored in our translations file en.js section: { title: 'This value is a string and it works perfectly', highlighted: [ { title: 'Highlighted title 1', text: 'Highlighted text ...

Global jQuery variables are unexpectedly coming back as "undefined" despite being declared globally

I need to save a value from a JSON object in a global variable for future use in my code. Despite trying to declare the country variable as global, it seems like it doesn't actually work. $.getJSON(reverseGeoRequestURL, function(reverseGeoResult){ ...

Creating an interactive Table of Contents in Sharepoint using only JavaScript

Imagine you have a massive Sharepoint wiki page filled with various heading tags like H1, H2, H3, and H4 - now picture creating a dynamic Table of Contents using these tags. The goal is to categorize these tags by group and utilize the HTML <detail> ...

Creating a Duplicate of the Higher Lower Challenge Game

To enhance my comprehension of React, I am constructing a replica of the website: Instead of utilizing Google searches, I opted for a dataset containing Premier League stadiums and their capacities. Up to this point, I have crafted the subsequent script: ...

Leveraging the power of jQuery/javascript in conjunction with Google Forms

Currently, I am attempting to utilize jQuery and JavaScript with an iframe that contains a Google form. The code snippet is displayed below: <body> <iframe id="myFormFrame" src="https://docs.google.com/forms/d/smfjkafj809890dfafhfdfd/viewform?emb ...

Having trouble getting Vue.js hello world to display on the page

I am attempting to create a Hello World app following the Vue.js site's get started documentation. Everything seems to be in order, but only the HTML code is being displayed on the page. Vue version: 1.0.26 Below is the HTML code: <!DOCTYPE ht ...

The error "Unable to access properties of undefined (reading x)" occurred while using the Array.prototype.find() method

In my Typescript project, I have an array of objects and I need to extract the value of a specific key based on a matching value in another key. I want to retrieve the sheetId value of the object where the title matches the value of fileName. Here is the ...

Introduce an additional parameter to the Prestashop Cart entity

After setting up a radiobox "stock_action" in the Cart, I need to send its value to the Cart object for additional order costs. In the Cart Override, the $stock_action variable has been added: public $stock_action; /** * @see ObjectModel::$defi ...

Node.js promises are often throwing Unhandled Promise Rejection errors, but it appears that they are being managed correctly

Despite my efforts to handle all cases, I am encountering an UNhandledPromiseRejection error in my code. The issue seems to arise in the flow from profileRoutes to Controller to Utils. Within profileRoutes.js router.get('/:username', async (r, s ...

Adjust the size of the wrapper/mask as the browser is resized

Is there a way to adjust the size of my wrapper and mask when the browser is resized? Currently, the mask stops once it's loaded, causing the content to be cut off when scrolling. You can view an example on this site. $(document).ready(function() { ...

Using the angular2-cookie library in an Angular 2 project built on the rc5 version

Starting a new angular2 rc5 project, I wanted to import the angular2 cookie module. After installing the module with npm, I made changes to my angular-cli-build.js file : npm install angular2-cookie edited my angular-cli-build.js file : module.exports ...

"The server responded with a 405 error message indicating that the requested method

I have been working on a registration form project using HTML, JS, NodeJS, and SQLite. However, I am encountering an issue with the fetch function when trying to post the inputted information into the database. I keep receiving a POST 405 (Method Not Allo ...

Tips for properly showcasing images on a webpage after ensuring all other content has loaded

Is there a way to have an image load last on a webpage after all other content has been loaded? I have an image that is retrieved from a database when a button is pressed, but I would prefer for the entire page to load first and then display the image. C ...

Storing the background color in a JavaScript variable

I've been experimenting with creating a fade in and out effect for a background image on a website. I've also been attempting to capture the background color of a div and store it in a variable. Here's what I have tried: elem = document.ge ...

Unexpected values being returned by Javascript/jQuery variables

Struggling with understanding scope in JavaScript, like many others before me. It can be quite challenging to navigate through the code at times. I've reviewed previous discussions on this topic, but I'm still having trouble applying it to my spe ...

Is it safe to utilize an AngularJS filter for parsing a URL?

When working on a web application, my client-side (angularjs based) receives JSON data from a web service. The JSON can contain a text field with some URLs, such as: blah blah ... http://www.example.com blah blah blah ... To render these links as HTML, I ...

Reimagining scrolling through content with a stylish unordered list (a sleek alternative to a select box

After having our company website redesigned by a professional designer, our site now looks much more visually appealing. However, I have encountered difficulties when trying to implement their design using HTML and CSS. One particular challenge is the heav ...