[英]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 將返回一個新數組,該數組通過回調中指定的條件。
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
splice 將完全刪除元素,同時改變長度並重新索引元素
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.