简体   繁体   中英

why I can't chain square braces after slice method?

I'm curios to know why on the snippet below return "Mango" rather than "M":

 var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
 var myBest = fruits.slice(-1)[0]
 console.log(myBest) // "Mango"

normally chaining square braces after string will dealing with it like an array:

var myBest = "Mango"[0]
console.log(myBest) // "M"

fruits is an array, and fruits.slice(-1) calls splice on the array fruits , and that call returns an array ( ["Mango"] ) and not a string.

The Array.prototype.slice() returns a shallow copy of a portion of an array into a new array object. In your case you have passed a negative one to it so it returns one element from the end of the old array in the new array object.

As it is a array,you are extracting what is at the 0th index. The 0th index in your case has the last element 'Mango' from the old array and not a string.

 var fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"]; var myBest = fruits.slice(-1); console.log(myBest) // Is an array console.log(myBest[0]) // "Mango"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM