作者:手机用户2702933671_440 | 来源:互联网 | 2023-01-12 21:13
我在Javascript中使用Array.pop函数有一个问题.Array.pop删除并返回Array的最后一个元素.我的问题是:是否有可能删除并返回数组的最后两个元素并返回它们而不是最后一个?
我使用此函数返回URL的最后一个元素,如下所示:
网址:www.example.com/products/cream/handcreamproduct1
'url'.splice("/").pop(); -----> "handcreamproduct1"
我想要的是:
'url'.splice("/").pop(); -----> "cream/handcreamproduct1"
我想在url中取最后两个参数并返回它们,使用.pop我只得到最后一个.请记住,URL是动态长度.网址可能如下所示:
网址:www.example.com/products/cream/handcreamproduct1
或
网址:www.example.com/products/handcream/cream/handcreamproduct1
Ori Drori..
8
拆分数组,使用Array#slice获取最后两个元素,然后使用slashes使用Array#join:
var url = 'www.example.com/products/cream/handcreamproduct1';
var lastTWo = url
.split("/") // split to an array
.slice(-2) // take the two last elements
.join('/') // join back to a string;
console.log(lastTWo);
1> Ori Drori..:
拆分数组,使用Array#slice获取最后两个元素,然后使用slashes使用Array#join:
var url = 'www.example.com/products/cream/handcreamproduct1';
var lastTWo = url
.split("/") // split to an array
.slice(-2) // take the two last elements
.join('/') // join back to a string;
console.log(lastTWo);