如何在JS数组中隐藏未定义的最后一个元素

huangapple go评论57阅读模式
英文:

How toInvisible Undefined last element in JS array

问题

console.log(transX); //正确:打印长度为 91 的数组(尽管带有小数的数字出现在末尾,原因不明)
console.log(transY); //正确:打印长度为 91 的数组
console.log("first");
console.log(transX[0]); //正确:打印 1
console.log("Last");
console.log(transX[-1]); //不正确:打印 "undefined" 而不是最后一项

let xd = transX.pop();
console.log("xd: " + xd); //可以正常运行,正确打印 transX 中的最后一项

为何在使用切片时 "undefined" 被视为数组元素,但在使用 pop() 时不被视为数组元素呢?

如何能够获得不包含 undefined 元素的数组?

英文:

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?

答案1

得分: 1

JavaScript不支持使用方括号表示的负数数组索引。但是,您可以使用Array#at与负数索引。

let arr = [1, 2, 3];
console.log(arr[-1]); // 错误
console.log(arr.at(-1)); // 获取最后一个元素
英文:

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

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

let arr = [1,2,3];
console.log(arr[-1]); // wrong
console.log(arr.at(-1)); // get last element

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年2月14日 02:51:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/75440081.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定