Would this be the right way to select elements that have a “.subj” ending?
-
28-09-2019 - |
문제
I have this code:
for(var i=0; i < localStorage.length; i++) {
var subjects = [];
var key, value;
key = localStorage.key(i);
value = localStorage.getItem(key);
var keysplit = key.split(".");
if(keysplit[keysplit.length] == "subj") {
subjects.push(value);
}
}
I am trying to select all the keys that have a .subj ending, but this does not seem to work. Any ideas?
해결책
The length
property returns the number of items in the array, and as the index is zero based there is no item with that index.
Use length - 1
to get the last item:
if (keysplit[keysplit.length - 1] === "subj") {
다른 팁
Other possibilities:
if(key.substr(key.lastIndexOf('.')) == ".subj")
//or
var suffix = '.subj';
if(key.lastIndexOf(suffix) == key.length - suffix.length)
See: lastIndexOf
제휴하지 않습니다 StackOverflow