2017-07-26 67 views
-3

我需要下面的js代码的解释,[1]在功能上做了什么?

function getURLParameter(url, name) { 
    return (RegExp(name + '=' + '(.+?)(&|$)') 
    .exec(url)||[,null])[1]; 
} 

var id = getURLParameter(url, 'id'); 
console.log(id); //1 

// let say the example of url is 
// index.php?id=1&user=xxx 

什么是[1]在返回语句中使用的呢?

我迷惑于它是如何获得的值为1的ID

+0

它访问所述阵列的所述第二元件。 – Li357

+0

您可以进行调试并查看自己。 – Batman25663

+2

'.exec(URL)的返回值'可能是一个数组。万一'.exec(URL)'不返回一个数组,我认为'|| [,空])'默认在'[,空]'作为数组索引到,最后的'[1]'索引到当前正在操作的值的任何数组中。所以,你应该要么得到通过.exec(URL)返回的数组或一个空的第二个元素,如果.exec(URL)返回null。但正如@ Batman25663所说,你应该通过调试来验证。 – anandsun

回答

2

RegExp.prototype.exec()返回数组,包括正则表达式(或null)的比赛。

[1]只是访问该数组中的第二个元素—在这种情况下正则表达式中捕获组的值。

它是等效于:

function getURLParameter(url, name) { 
    var regexp = new RegExp(name + '=' + '(.+?)(&|$)'); 
    var result = regexp.exec(url); // array containing the full string of 
           // characters matched, the value of the 
           // capturing group and the end anchor 
           // (or null) 
    if (Array.isArray(result)) { 
    return result[1]; 
    } else { 
    return null; 
    } 
} 
+0

不错,您还提供了这个非紧凑的代码视图。更容易理解,会帮助OP我想。 – Zabuza

+0

事实上,3个元素,而不是2。全场比赛的非常好的答案 – Luca

+1

阵列(0),id值(1),和端锚(2) – Tezra