为什么不能 console.log 打印倒序索引 [-1]

why can't console.log print with backward order index [-1]

我是 JavaScript 的新手。请帮助。

我正在玩这个方法 - console.log。这是我所做的:

let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Neapolitan", "Mint Chip"];
delete iceCreamFlavors[iceCreamFlavors.length-1];
console.log(iceCreamFlavors[length-1])

控制台返回

undefined

如果我这样做:

console.log(iceCreamFlavors[5])

打印没问题

Mint Chip

但如果我这样做:

console.log(iceCreamFlavors[-1])

它回来了

undefined

所以我的问题是为什么 console.log 不能以倒序使用索引号? 可能在现实中用处不大,只是好奇

delete 关键字用于删除 Object 属性而不是数组元素,删除数组元素使用 Array.prototype.filter()Array.prototype.splice()

Splice 将修改原始数组,而 filter 将 return 一个通过回调中指定条件的新数组。

let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Neapolitan", "Mint Chip"];
iceCreamFlavors.splice(5, 1);
console.log(iceCreamFlavors);

let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Neapolitan", "Mint Chip"];
const filter = iceCreamFlavors.filter(x => x != 'Mint Chip');
console.log(filter);

注意:您可以使用array[index]访问数组元素,索引的范围是0 to array.length - 1。数组从 0 索引开始,这意味着第一个元素的索引为 0,第二个元素的索引为 1,依此类推

let iceCreamFlavors = ["Chocolate", "Strawberry", "Vanilla", "Pistachio", "Neapolitan", "Mint Chip"];
iceCreamFlavors.splice(5, 1);
console.log(iceCreamFlavors.length); // array length
console.log(iceCreamFlavors[iceCreamFlavors.length - 1]); // last element
console.log(iceCreamFlavors[0]); // first element

数组中删除vs拼接

delete 不会改变长度或重新索引数组,给定的元素被删除但它显示为 undefined

拼接将完全删除元素以及更改长度并重新索引元素