0

I have a Javascript array, full_range:

const range1 = _.range(1, 10, 0.5);
const range2 = _.range(10, 100, 5);
const range3 = _.range(100, 1000, 50);
const range4 = _.range(1000, 10000, 500);
const range5 = _.range(10000, 105000, 5000);
const full_range = range1.concat(range2).concat(range3).concat(range4).concat(range5);

I then loop over this array and populate another array.

var transY= [];
var transX= [];
for(let i = 0; i < full_range.length; i++){
    let y = getTrans(full_range[i], dampingFactor, natFreq); //returns a float
    transY.push(y);
    transX.push(parseFloat(full_range[i]));
    }

The result is then returned to another function where:

console.log(transX); //Correct: Prints Array of 91 length (although the numbers with //decimals are at the end for some reason
console.log(transY); //Correct: Prints Array of 91 length
console.log("first");
console.log(transX[0]); //Correct: Prints 1
console.log("Last"); 
console.log(transX[-1]); //Incorrect: Prints "undefined instead of the last item

let xd = transX.pop();
console.log("xd:" + xd); //Works and correctly prints the last item in transX

The goal is to graph this dataset on a BokehJS graph, which does weird things when the last value is undefined.

Why is "undefined" being treated as an array element using slicing, but not when using pop()?

How would I be able to get the array without the undefined element?

mrblue6
  • 587
  • 2
  • 19
  • "*//Incorrect: Prints "undefined instead of the last item*" it's quite correct. There is nothing at the nonexistent property called `-1` thus you get `undefined`. Same as if you tried `transX["fred"]` or `transX["seahorse"]`. "*Why is "undefined" being treated as an array element using slicing*" because JS is not Python and does not need to behave like Python. In fact, it's Python that's the odd one out - in C, C++, and Java, `foo[-1]` will not access the last element. It will do different things (like "not compile" in Java) but not what Python does. – VLAZ Feb 13 '23 at 19:04

1 Answers1

1

Negative array indexing (with bracket notation) is not supported in JavaScript. However, you can use Array#at with negative indexes.

let arr = [1,2,3];
console.log(arr[-1]); // wrong
console.log(arr.at(-1)); // get last element
Unmitigated
  • 76,500
  • 11
  • 62
  • 80