JavaScript Array slice() Method: Removing the Last Element

const fruits = ['apple', 'banana', 'orange', 'mango', 'kiwi'];
const result1 = fruits.slice(0,-1);
console.log(result1);

Output:

['apple', 'banana', 'orange', 'mango']

Explanation:

The slice() method creates a shallow copy of a portion of an array, returning a new array object. In this example, the original array is fruits. The first argument in slice() is the starting index (0 in this case). The second argument is the ending index (-1 in this case).

When the second argument is negative, it represents the position relative to the end of the array. So, -1 indicates the last element. Therefore, slice() returns all elements from index 0 up to, but not including, the last element.

The result is stored in a new variable called result1, which is then displayed in the console. The output is ['apple', 'banana', 'orange', 'mango'].

JavaScript Array slice() Method: Removing the Last Element

原文地址: https://www.cveoy.top/t/topic/mupk 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录