Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
285 views
in Technique[技术] by (71.8m points)

javascript - 获取Javascript数组中的最后一项(Get the last item in an array in Javascript)

Here is my JavaScript code so far:

(到目前为止,这是我的JavaScript代码:)

var linkElement = document.getElementById("BackButton");
var loc_array = document.location.href.split('/');
var newT = document.createTextNode(unescape(capWords(loc_array[loc_array.length-2]))); 
linkElement.appendChild(newT);

Currently it takes the second to last item in the array from the URL.

(当前,它需要URL中数组的倒数第二个项目。)

However I want to do a check for the last item in the array to be "index.html" and if so, grab the third to last item instead.

(但是,我想检查数组中的最后一项是否为“ index.html”,如果是,请改为抓取倒数第三项。)

  ask by balexander translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
if(loc_array[loc_array.length-1] == 'index.html'){
 //do something
}else{
 //something else.
}

In the event that your server serves the same file for "index.html" and "inDEX.htML" you can also use: .toLowerCase() .

(如果您的服务器为“ index.html”和“ inDEX.htML”提供相同的文件,则您也可以使用: .toLowerCase() 。)

Though, you might want to consider doing this server-side if possible: it will be cleaner and work for people without JS.

(但是,如果可能的话,您可能要考虑在服务器端进行此操作:它将更加干净,并且可以在没有JS的情况下使用。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...