Tips for utilizing a personalized technique on an array

Can you explain why a custom method on an array is not functioning properly in this scenario?

function runTestMethod() {
    alert("method running");
}

String.prototype.testMethod = runTestMethod;


var A = "A";
A = A.testMethod();         // This works


var B = new Array();
B[0] = "food";
B[1] = "bar";

B = B.testMethod();         // This results in an error 'undefined' is not a function

B[0] = B[0].testMethod();       // This also throws an error 'undefined' is not a function

B[0] = B[0].slice(0,-1);        // This works

UPDATE: The reason for this issue is that I am attempting to use a String.prototype on an array. My method should actually be Array.prototype instead. Even though array "B" contains string elements, they are still treated as array-object-properties rather than actual strings. The behavior of the slice() method is confusingly designed to work on both strings and arrays. Special thanks to T.J. Crowder for providing clarification on this matter.

Answer №1

By assigning it to String.prototype instead of Array.prototype, the method is accessible on strings rather than arrays.

Here is the line in question:

String.prototype.testMethod = runTestMethod;

So, by adding it to String.prototype, the property and function are available for use on strings. To make it available on arrays instead, it should have been added to Array.prototype.

Here is a complete example:

// v--- Note how this is added to `Array.prototype`!
Array.prototype.oddsOnly = function() {
    var result = [], i;
    for (i = 1; i < this.length; i += 2) {
        result.push(this[i]);
    }
    return result;
};

// These are arrays
var a = ["zero", "one", "two", "three", "four", "five", "six"];
var b = a.oddsOnly();
//         ^------------- function is available on arrays
console.log("a: " + a.join(", "));
console.log("b: " + b.join(", "));

Link to Live Example | Link to Live Source

Output:

a: zero, one, two, three, four, five, six
b: one, three, five

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

Angular controller fails to fetch scope variable in subsequent view

I'm currently working on implementing a login feature that directs a validated user to a personalized HTML view that greets them with their name. The initial view is a login page. When the user clicks the "Log In" button, the ng-click function is sup ...

Adding new elements to an array does not activate the reactivity of Vue

After discovering that editing objects within an array doesn't function properly in vue.js due to its limitations, I tried using vue.set to resolve the issue, but it's proving to be quite challenging for me. Let's take a look at the sample ...

Using Alpine JS to rotate through images at regular intervals using the window.setInterval() method

Attempting to tackle a simple task using Alpine JS and the standard JS function setInterval. The goal is to create an image selector where images switch every second (1000ms). Here's what I have so far: <div x-data="imgFunc()"> ...

Executing mathematical operations with floating point numbers using JavaScript in Python

I’m creating a Python program that interacts with a web application that I didn’t develop. There is some data that needs to be represented in my program which isn’t directly sent to the client by the server, but is instead calculated separately on bo ...

Error injecting angular.bootstrap in Angular 1.6.5 version

I have a MeanJS.org skeleton app that I've transformed into hapi-js from express, switched to postgres from mongo, and incorporated OAUTH for authentication (mainly because I liked the server/client module folder structure - haha). Everything seems t ...

Making an Ajax request by leveraging the power of an image tag

I am facing a challenge with trying to establish communication on my server between port 80 and port 8080 through an ajax request. I understand the implications of CORS and the cross domain request origin policy, as well as the potential solution involving ...

Is there a way to generate a 2D array composed of 2D character arrays?

Looking to create a 2D array in Java that consists of [3][3] elements, with each element being a 3x3 character array. Any tips on how to achieve this? ...

Having trouble accessing variable values within the nth-child selector in JavaScript

I am attempting to utilize the value of a variable within the element selector p:nth-child(0). Instead of hardcoding the number as 0, I want to dynamically assign the value of a variable. In this case, the variable is represented by i in a for loop. Howev ...

$http({method}) is malfunctioning while $http.get is functioning properly

Issue Description: While working on my project, I encountered an issue where using $http({ method : 'GET', url : data : ..... param works fine for both GET and POST requests. However, when the same method is used in JSFiddle, it blocks my reques ...

What is the proper way to specify a file destination in React?

After reading this article on downloading objects from GCP Cloud storage bucket, I'm curious about setting the file destination dynamically in React. Is there a way to achieve this? The article can be found at: https://cloud.google.com/storage/docs/do ...

Incorporating mimes into ASP .NET MVC

Quick question: I've been trying to enable file extensions in my MVC application by editing the Web.config file, but it doesn't seem to be working. Is there anything else I need to do? <system.webServer> <staticContent> <mimeMa ...

Sending data using jQuery's AJAX feature

Here is an example of the code I have: var loadUrl = 'test.php'; var dataObject = { category_id: category_id, grade_val: grade }; jQuery.ajax({ type: 'POST', url: loadUrl, data: dataObject, dataType: 'html', ...

What is the method for updating the form action to alter the hash without causing a page reload?

My website is designed to show dynamic data based on the information following the '#' in the URL. Surprisingly, when I manually change this value in the URL, the page doesn't reload. However, if I modify it within a form on the site, the we ...

Is it possible to have an Iframe that contains content but no src attribute?

During the process of troubleshooting jQuery code on their website (using the Chrome Developer Toolbar), I came across an interesting observation. I found that their examples were embedded within an Iframe: Here, for instance, there is a sample displayed ...

Transform the array of strings

I'm currently working with an array that looks like this: ["[Date.UTC(2016,09,30),250500.00]","[Date.UTC(2016,09,29),255100.83]", "[Date.UTC(2016,09,28),255600.82]"] What would be the best way to transform it into a structure like this? [[Date.UTC( ...

What is the process for retrieving a value from a Django view?

Would it be feasible to call a view from a JavaScript file using Ajax and have the view only return a specific value known as "this"? However, despite attempting this, an error occurs stating that the view did not provide an HttpResponse object, but instea ...

Trouble arises when attempting to append a class through ng-class upon clicking

In a specific scenario, I am trying to change the border color from black to red in a div by appending a class using ng-class when clicked. However, when clicking a button, the modal opens but the class is not being appended as expected. <div ng-class ...

Error encountered during the prerendering process on Vercel's Next.js build

While trying to compile my website on Vercel, I encountered a pre-rendering error during export. Does anyone know why this is happening and can provide assistance? Here is the link to my GitHub repository where all the code is stored: https://github.com/M ...

Kendo's data-bind onclick feature functions properly on web browsers but fails to work on mobile devices

As a newcomer to Kendo and JavaScript, I may be missing something obvious... In one of my list entries, I have a simple call like this: <li style="margin: 0.5em 0 0.5em 0"> <a href="#transaction-details" data-bind="click: onB ...

Encountering an issue while attempting to fetch a value from a nested object property with VueJS Interpolation

I'm struggling to properly display nested arrays in Vue JS. Below is a snippet of my JSON data: { "id": 1, "slug": "test-page", "banner": { "title": "banner title", "subTitle": "my sub title", "hasSubTitle": false, "hasClass": " ...