为什么无法控制台.log使用反向顺序索引打印 [-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()

拼接将修改原始数组,而过滤器将返回一个通过回调中指定条件的新数组。

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

阵列中的删除与拼接

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

拼接将完全移除元件,同时改变长度并重新索引元件

相关内容

  • 没有找到相关文章

最新更新