문제

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top