The .push method in Javascript is failing to execute

I'm facing a challenge with this particular code snippet. Essentially, I am attempting to loop through an array of Word objects and categorize them based on word type using a switch statement. This process is triggered by jQuery listening for a button click.

for (var i=0; i < wordList.length; i++)
{
    switch (wordList[i].type) {
        case "1": nouns.push(wordList[i].word); break;
        //"1" represents a noun type, and the "word" property contains the actual word string
        ... //Additional cases for other word types
    }
}

Initially, the words were not being added to the nouns array. So, I modified the line under case "1" as follows:

case "1": nouns.push(wordList[i].word); asdf = nouns; asdf2 = wordList[i].word; break;

By omitting 'var', asdf and asdf2 unintentionally became global variables, allowing me to interact with them in the console:

asdf
asdf2

Displayed [] and "I", respectively, showing that the word was successfully retrieved, but not appended to the array.

asdf.push(asdf2)

Resulted in 1, and upon further inspection of asdf, it showed ["I"].

Any insights on what might be causing this issue?

Edit: Including full relevant code snippet

//Declare arrays
var articles=[], properNouns=[], nouns=[], pluralNouns=[], adjectives=[], conjunctions=[], verbs=[], pluralVerbs=[], adverbs=[], prepositions=[], interrogatives=[];

//Organize words into respective arrays
for (var i=0; i < wordList.length; i++)
{
    switch (wordList[i].type) {
        case "1": nouns.push(wordList[i].word); asdf = nouns; asdf2 = wordList[i].word; break;
        case "11": pluralNouns.push(wordList[i].word); break;
        case "12": properNouns.push(wordList[i].word); break;
        case "2": verbs.push(wordList[i].word); break;
        case "21": pluralVerbs.push(wordList[i].word); break;
        case "3": adjectives.push(wordList[i].word); break;
        case "4": adverbs.push(wordList[i].word); break;
        case "5": conjunctions.push(wordList[i].word); break;
        case "6": prepositions.push(wordList[i].word); break;
        case "7": interrogatives.push(wordList[i].word); break;
        case "8": articles.push(wordList[i].word); break;
        default: console.log("Error, could not sort "+wordList[i].word); break;
    }
}

Answer №1

Check out this JSFiddle demo.

Here are the specific modifications made in the example:

  • Definition of wordList has been added.

  • A div tag is used in the JSFiddle example to append output.

The code seems to meet your requirements. Could your definition of wordList be different from what's shown here?

    $(document).ready(function () {
    //Declare arrays
    var articles = [], properNouns = [], nouns = [], pluralNouns = [], adjectives = [], conjunctions = [], verbs = [], pluralVerbs = [], adverbs = [], prepositions = [], interrogatives = [];

    var wordList = [{ 'type': "1", 'word': 'foo' },
         { 'type': "1", 'word': 'foo1' },
         { 'type': "1", 'word': 'foo2'}, 
         { 'type': "1", 'word': 'foo3' }];

    //Sort words into appropriate arrays
    for (var i = 0; i < wordList.length; i++) {
        switch (wordList[i].type) {
            case "1":
                nouns.push(wordList[i].word);
                asdf = nouns;
                asdf2 = wordList[i].word;
                break;
            case "11":
                pluralNouns.push(wordList[i].word);
                break;
            case "12":
                properNouns.push(wordList[i].word);
                break;
            case "2":
                verbs.push(wordList[i].word);
                break;
            case "21":
                pluralVerbs.push(wordList[i].word);
                break;
            case "3":
                adjectives.push(wordList[i].word);
                break;
            case "4":
                adverbs.push(wordList[i].word);
                break;
            case "5":
                conjunctions.push(wordList[i].word);
                break;
            case "6":
                prepositions.push(wordList[i].word);
                break;
            case "7":
                interrogatives.push(wordList[i].word);
                break;
            case "8":
                articles.push(wordList[i].word);
                break;
            default:
                console.log("Error, could not sort " + wordList[i].word);
                break;
        }
    }
    for (var i in nouns) {
        console.log(nouns[i]);
        $('#output').append(nouns[i] + '<br>');
    }
    console.log(nouns);
});

Answer №2

The root cause of the issue: An alteration was made to a data file resulting in improper tagging of VERBS, which ultimately prevented any sentences from being generated.

Reason for the empty array: The system being used processed the arrays by inadvertently emptying them, and the newly introduced variable asdf simply pointed to the now empty array when accessed in the console.

A way this could have been prevented:

case "1": nouns.push(wordList[i].word); asdf = nouns.slice(0); break;

Consider this as a friendly reminder: Always make a copy of your array during debugging processes.

Answer №3

Indeed - resurrecting an ancient thread...

I encountered the exact same issue today. It took me some time to realize that a Watch Expression in the Chrome Debugger was causing the array to be emptied.

Therefore, my code for pushing looked like this:

$scope.emailMsg.Bcc.push(EmailAddress);

The watch expression in the debugger was set up like this:

$scope.emailMsg.Bcc = [];

As a result, every time I stepped through my array, it would reset to zero :)

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

Convert a JSON object into a new format with a nested hierarchy

The JSON object below is currently formatted as follows: { "id": "jsonid", "attributes": { "personName": { "id": "name1", "group": "1.1" }, "ag ...

Converting User Input Special Characters to HTML5 data-attributes with URL Encoding/Decoding

Seeking assistance from the experts on my first question here at stackoverflow. Our web application allows users to input escape/special characters, and we are conducting testing for extreme scenarios. I have successfully passed escape characters through a ...

Utilizing absolute path in Typescript: A comprehensive guide

I am currently working on a project written in Typescript running on NodeJS. Within the project, I have been using relative paths to import modules, but as the project grows, this approach is becoming messy. Therefore, I am looking to convert these relativ ...

"Can you explain the method by which reveal.js adjusts the size of

I have been exploring the resizing behavior of elements in reveal.js and trying to understand how they dynamically adjust. If you resize the page height, you can observe that the elements shrink up to a certain extent along with the page. However, when in ...

Best return type for a webservice triggered using jQuery but not requiring any data to be returned

I am currently working on a web service that utilizes several methods. These methods do not have significant impact on the client side as I call them using jQuery/ajax. My main concern is regarding the recommended return type. Typically, I would return JS ...

What are the implications of dynamically setting or changing event handlers in web development?

Looking to streamline the process of replacing standard confirm() boxes with Bootstrap modals for saving and deleting on a page. Each operation has its own button (referred to as the action button) which triggers the corresponding modal. Upon clicking the ...

Utilizing a shared service for multiple JSON datasets in AngularJS: A beginner's guide

After successfully creating a service that retrieves data from a local JSON file and uses it in a controller to display it in the browser, everything seems to be working well. Here is the code snippet: JavaScript Code: var myApp = angular.module("myApp", ...

Ways to stop VoiceOver from selecting the background content when a modal is open

Is there a way to prevent VoiceOver from reading the content behind a modal? I tried using aria-modal=true, but it seems VoiceOver does not support this feature by default like NVDA and JAWS do. I found more information about this on . According to the in ...

Organize inputted strings in C

Is there a way to dynamically input strings using C? The input should consist of words made up of letters. Where 0 < the number of words N < 1000 And the maximum length of a word is <= 30 For example, the input could be: gh a b f cde Addition ...

Updating items within a nested list in Redux can be achieved by carefully managing the state and implementing actions to add or remove

My current state is set up like this: Fruits: { 34: { FruitsID: 34, FruitsList:{apple, pineapple, banana} } } I want to update my fruit list by adding 'peach' and 'pear', while also removing 'apple&apos ...

Using Javascript to test a specific item in an asp Listbox

Let's consider a scenario where there is ListBox1 containing the following listitem: <asp:ListItem Value="No.1">No.1</asp:listitem> In addition, we have a label for a test purpose: <asp:Label ID="lblLabel" runat="server" Text="Label ...

Troubleshooting issues with ASP.NET bundling and minification when using Angular.js

After reviewing many questions on the same topic, none of them were able to solve my specific case. Our current challenge involves bundling and minifying AngularJs files within .Net code. The following code snippet shows how we are bundling our files insi ...

Utilize npm to construct a Vue application and execute it on a Raspberry Pi device

My roommate and I are currently working on a Vue app project together, and we're aiming to deploy it on our Raspberry Pi. We're wondering if there's a way to npm build the final app on our PC and simply start the server on the Pi without hav ...

How can I retrieve and manipulate the text within an option tag of a form using JavaScript?

<select name="products"> <option value=""> - Choose - </option> <option value="01">table</option> <option value="02">chair</option> <option value="03">book</option> <option value= ...

What is the TypeScript equivalent of the Java interface.class?

Can you write a Java code in TypeScript that achieves the same functionality as the code below: Class<?> meta = Object.class; and meta = Processor.class; // Processor is an interface In TypeScript, what would be the equivalent of .class? Specifica ...

Encountering an unexpected token error while building an Angular4 --prod project that involves Three

Encountering an error while trying to build an Angular4 project in production with the following command: node --max_old_space_size=8192 'node_modules/@angular/cli/bin/ng' build --prod --output-hashing=al Error: ERROR in vendor.422622daea37e ...

Convert the text inside a span element into a key-value object in JavaScript

How can I extract and save the text from a span element as key value pairs within a div? <div class="data-diff-span__composite-list-item__18c5zip data-diff-core__highlight-area__19c0zip"> <div class="data-diff-basic__class-row__4n ...

Show a dynamic Swiper carousel upon selecting a thumbnail in an image gallery

I am in the process of creating a thumbnail gallery that includes a slider feature using Swiper. The default setup has the slider hidden, and once an image is clicked, the slider should appear with the selected image. To close the slider and return to the ...

Optimizing Performance by Managing Data Loading in JavaScript Frameworks

I am new to JavaScript frameworks like React and Vue, and I have a question about their performance. Do websites built with React or Vue load all data at once? For example, if I have a page with many pictures, are they loaded when the component is used or ...

Is it possible to import data into a script?

When working with Angular, I am attempting to: $scope.data = "<script> alert('hi'); </script>"; Unfortunately, this approach does not seem to be effective. I also experimented with adding ng-bind-html but did not achieve any success ...