Pergunta

Eu tenho este código:

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);
   }

}

Estou tentando selecionar todas as teclas que têm um final .Subj, mas isso não parece funcionar. Alguma ideia?

Foi útil?

Solução

o length A propriedade retorna o número de itens na matriz e, como o índice é baseado em zero, não há item com esse índice.

Usar length - 1 Para obter o último item:

if (keysplit[keysplit.length - 1] === "subj") {

Outras dicas

Outras possibilidades:

if(key.substr(key.lastIndexOf('.')) == ".subj")
//or
var suffix = '.subj';
if(key.lastIndexOf(suffix) == key.length - suffix.length)

Ver: lastIndexOf

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top