Javascript's array slice method can exhibit some unorthodox behavior

Encountered a peculiar array anomaly when used within a class... Attempted to unravel the mystery, but couldn't quite grasp it. So here's what went down.

class weirdArray{
  constructor(){
    this.array=[0,2,3];
    this.fn=this.fn.bind(this);
  }
  fn(){
    console.log(this.array.slice(0,this.length));// will print [0,2,3]
    console.log(this.array.slice(0,this.length-1));// will print an empty array
  }
}
const obj=new weirdArray();
obj.fn();

It functions perfectly when attempting to access the entire array using this.array.slice(0,this.length). It returns the complete array. However, upon trying to retrieve an array without the last element with

this.array.slice(0,this.length-1)
, instead of the expected output, an empty array is returned. This issue seems to only arise within a method of an object. The expected behavior is exhibited under normal circumstances.

const array=[0,2,3];
console.log(array.slice(0,this.length-1)); // will print [0,2]

Even after removing the bind method to test its impact on the behavior, the result remains constant...

Any insights as to why this phenomenon occurs?

Answer №1

Your code is incorrect; you should use this.array.length - 1

It seems that this.length is undefined

Based on our discussion, it appears you are attempting to inherit from the DOM Array

Here is a way to properly inherit from Array:


class MyArray extends Array {
   constructor(props){
    super();
    for(var i=0;i<arguments.length;i++) this.push(arguments[i]);
   }
}

const k = new MyArray(5,6,7,8);
console.log(k.length);

Answer №2

There seems to be an issue related to the 'this' keyword within the slice method. The problem arises when trying to access the length property of an object that is 'undefined'. As a result, subtracting 1 from undefined leads to NaN.

Your code can be simplified and rewritten as:

class example{
  constructor(){
    this.array=[0,2,3];
  }
  fn(){
   let length = this.array.length;
    console.log(this.array.slice(0, undefined)); // Output: undefined due to the absence of a defined length
    console.log(this.array.slice(0, NaN)); // Output: NaN because undefined - 1 equals NaN
  }
}
const instance=new example();
instance.fn();

To resolve this issue, consider using the following amended code:

class example{
  constructor(){
    this.array=[0,2,3];
  }
  fn(){
   let length = this.array.length;
    console.log(this.array.slice(0, length)); // Output: [0,2,3]
    console.log(this.array.slice(0, length-1)); // Output: [0,2]
  }
}
const instance=new example();
instance.fn();

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

Guide to handling URL errors in a form using AngularJS

I'm currently working on implementing URL validation for my form. The validation itself is working properly, but I've encountered an issue. Previously, I had validation set up so that an error message would display when submitting the form with e ...

What is the process for connecting this to React ES6 getter and setter methods?

When utilizing this within an ES6 function, it is necessary to explicitly declare it in the constructor. export class MyComponent extends React.Component { constructor(){ super(); this.myFunc = this.myFunc.bind(this); } ...

Error encountered in TypeScript Yarn application during download process: SyntaxError: Unforeseen symbol '.'

Today marks my first experience using yarn for applications, and unfortunately, I've encountered a frustrating issue: SyntaxError: Unexpected token '.' at wrapSafe (internal/modules/cjs/loader.js:915:16) at Module._compile (internal/ ...

Error TS2345: The provided argument 'Observable<TodoInterface[]>' does not match the expected parameter type 'TodoInterface[]'

Currently, I am experimenting with some new ideas in a project and encountered an error message as mentioned in the title. To begin with, I have a BehaviorSubject array where all my items are stored: todos$ = new BehaviorSubject<TodoInterface[]>([]) ...

Ensure that the line above is shorter in length compared to the following line

Is there a way to ensure that the previous line of text is always shorter than the next one, even if the length of the text is unknown? For example: Lorem ipsum dolor sit amet, consectetur adipiscing et libero posuere pellentesque. Vivamus quis nulla jus ...

Cordova triggers a 500 (Internal Server Error) when making an Ajax request

When I send an ajax request, it works fine in the browser but returns an internal error when sent within a Cordova APK. Upon comparing the headers, I noticed that the only difference is in the ORIGIN: The one not working has origin: file:// POST 500 (In ...

Tips for integrating a logo into router view animations

How can I incorporate a logo into the white fade-in screen that appears when navigating between subpages using <router-view> within App.vue? Here is a simplified version of my App.vue code: <template> <div id="app"> <div ...

Error Encountered when Using JQuery AJAX: Unexpected Identifier Syntax Issue

I've been struggling with a strange error for quite some time now. I want to believe that this is one of those errors where the solution will magically appear, but only time will tell. Here's the piece of code causing the issue: var images = ...

Guidelines on extracting information from a POST request, evaluating it based on a specified criteria, and providing a corresponding feedback

I'm on the hunt for a simple solution to facilitate communication between the front-end and back-end. What I envision is creating a basic JavaScript front-end client where a user can enter a number between 1 and 10,000 to guess a random number genera ...

Why does my Visual Studio Code always display "building" when I launch an extension?

https://code.visualstudio.com/api/get-started/your-first-extension I followed a tutorial to create a hello world extension. Why does my VSCode always display 'building' when I run the extension? Executing task: npm run watch < [email p ...

What is the correct way to send a basic array through an AJAX call?

I have the code below: $("form").submit(function(e) { e.preventDefault(); var answers = new Array(); for (var j = 0; j <= i; j++) answers[j] = [($("[name=ris" + j + "]").val())]; $.ajax({ url: "crea_sondaggio.php ...

Develop a cutting-edge Angular application enhanced with Firebase authentication and integrated with Node.js and MongoDB

I'm in the midst of planning the architecture for my web app and I wanted to get your opinion on whether using Firebase auth with Angular and mongoDB as a database is a good idea. (I prefer not to use Firestore real-time database) Would it be benefic ...

Is there a Rails 3 equivalent to $(document).ready() for ensuring that Highcharts loads correctly?

I am facing an issue with my highcharts chart not loading. I am looking for a way to delay the execution of the JavaScript file containing the chart data until after the partial has been passed into building the full page. Can someone provide guidance on ...

Fortran subroutine: Sending array size of Common block as parameter

I need to pass the array dimension as a placeholder variable to a subroutine while the array itself is stored in a common block. Below is the code I am working with: PROGRAM test integer i, nn integer PARAMETER(Nt=10) real x(Nt), y(nt), z(Nt) Common /Bdat ...

Setting up npm packages for a Node application

Currently working on developing an npm package for testing purposes and looking to incorporate TypeScript. However, the creation of a node_modules folder is unnecessary. Is there a way to install npm dependencies without generating the node_modules folde ...

Mastering the proper implementation of in_array with nested arrays

I need to use the in_array function to check if multiple integers, specifically the integer "427971780" with key amenityId, exist anywhere in an array of arrays. The structure of the array is: array(43) { [0]=> array(2) { ["amenityId"]=> int(427 ...

Ensure that an async function's result is resolved before rendering react routes

I've been working on setting up an authentication service in my single-page application using React in the routes file. The goal is to check if a user is trying to access a private path, and verify that the token stored locally is valid. However, I&ap ...

Leveraging 'fs' in conjunction with browserify

Exploring the functionality of fs in browserify Calling require('fs') results in an empty object being returned var fs = require('fs') ...

The arrangement of a JSON array can be modified by AngularJS' Ng-repeat functionality

Hello everyone at SO: On March 18, 2014, I encountered a situation while trying to use ng-repeat. The elements inside the array, retrieved from a Json string, seem to be changing their original order. To clarify, the initial variables in the array pertai ...

Issue with Angular JS failing to populate HTML content following an HTTP request

Today was my first day diving into AngularJS, following some tutorials on CodeSchool. I checked out this tutorial and this example to get started. The issue I'm facing is that although I successfully retrieved JSON data from the PHP server side (for ...