2011-01-21 21 views
12

Here è il mio esempio. Potete dirmi come posso fare la matrice ha i tasti consecutiviJavascript - Reindicando un array

array[0] 
array[1] 
array[2] 

quando ho

var testArray = new Array(); 
testArray[3]="qwerty"; 
testArray[7]="asdfgh"; 
testArray[13]="zxcvbn"; 
var testString = testArray.join(); 

Nota del redattore: Il richiedente vuole reindicizzare la sua matrice.

+1

rendere la matrice che cosa? – WarrenFaith

+1

Probabilmente vuole reindicizzare l'array, a giudicare dal suo violino. –

+0

@warren; nel mio esempio i tasti dell'array sono 3, 7, 13. Quando li serializzo diventa ",,, qwerty ,,,, asdfgh ,,,,,, zxcvbn". Quello che voglio è "qwerty, asdfgh, zxcvbn". – borayeris

risposta

8

Se non ti dispiace utilizzando JavaScript 1.6: (nota: questo codice utilizza la libreria jQuery)

var testArray = new Array(); 
testArray[3]="qwerty"; 
testArray[7]="asdfgh"; 
testArray[13]="zxcvbn"; 
var testString = testArray.filter(function (item) { return item != undefined }).join(); 

$(function(){ 
    $('#write').text(testString); 
}); 

filtro prototipo:

if (!Array.prototype.filter) 
{ 
    Array.prototype.filter = function(fun /*, thisp */) 
    { 
    "use strict"; 

    if (this === void 0 || this === null) 
     throw new TypeError(); 

    var t = Object(this); 
    var len = t.length >>> 0; 
    if (typeof fun !== "function") 
     throw new TypeError(); 

    var res = []; 
    var thisp = arguments[1]; 
    for (var i = 0; i < len; i++) 
    { 
     if (i in t) 
     { 
     var val = t[i]; // in case fun mutates this 
     if (fun.call(thisp, val, i, t)) 
      res.push(val); 
     } 
    } 

    return res; 
    }; 
} 
+0

Ho semplicemente copiato il suo codice da JsFiddle, ma inserirò un remake per altri utenti. Grazie per il testa a testa. – Exelian

+0

Grazie, Exalian. – borayeris

0

si vuol dire, senza le virgole? se è così basta fare questo var testString = testArray.join(""); o è possibile aggiungere qualsiasi carattere desiderato tra.

+0

Quello che mi serve è reindicizzare la matrice. Non questo. – borayeris

+0

potresti sempre unirti alla matrice e quindi ricollegarla con un certo delimitatore. Forse non è così professionale ma le sue 2 linee di codice. – elasticrash

+0

l'unione e la ridistribuzione non funzioneranno se gli elementi dell'array sono oggetti, ad esempio –

0

Prova Questo

var testArray=testArray.join(" "); 
+0

Ciò di cui ho bisogno è la reindicizzazione dell'array. Non questo. – borayeris

2
var testArray = new Array(); 
testArray[3] = "qwerty"; 
testArray[7] = "asdfgh"; 
testArray[13] = "zxcvbn"; 


var isEmpty = function(x) { 
    // returns true if x is null and false if it is not. 
    if(x!=null){ 
     return true; 
    }else{ 
     return false 
    } 
} 
var newArray=testArray.filter(isEmpty); 

var testString2 = newArray.join(); 

$('#write').text(testString2); 
2

Super semplice funzione:

function reindex_array_keys(array, start){ 
    var temp = []; 
    start = typeof start == 'undefined' ? 0 : start; 
    start = typeof start != 'number' ? 0 : start; 
    for(var i in array){ 
     temp[start++] = array[i]; 
    } 
    return temp; 
} 
testArray = reindex_array_keys(testArray); 

Nota: questo sarà soffiare via tutti i tasti personalizzati. il risultato sarà sempre indicizzato numericamente. è possibile aggiungere controlli per verificare se si tratta di un array o meno, ma io tendo a non utilizzare semplicemente le funzioni che costruisco in modo diverso da come sono destinate a essere utilizzate. è anche possibile avviare l'indice più alto se vi piace:

testArray = reindex_array_keys(testArray, 3); 

che produrrà 3 articoli 'indefiniti' all'inizio dell'array. puoi aggiungerlo successivamente, ma penso che sarebbe meglio fare testArray.unshift('newValue') prima di reindicizzare personalmente.

divertirsi

+0

Unchaught ReferenceError: i non è definito – fdrv

20

Array.prototype.filter() non viene eseguito su oggetti non definiti cancellati o precedentemente. Quindi puoi semplicemente fare:

testArray.filter(function(val){return val}); 

.. per ri-indicizzare il tuo array.

O ES6:

testArray.filter(val => val) 
+1

Ding ding ding - risposta più breve e non implica l'uso di operatori di confronto liberi. – aendrew

+2

Si noti che restituirà un nuovo array senza influire su 'testArray'. Potresti voler ridefinirlo: 'testArray = testArray.filter (val => val);' – pmrotule

+0

@pmrotule se vuoi tenerlo in giro, sì. Seguendo l'esempio nella domanda, il più breve sarebbe 'var testString = testArray.filter (val => val) .join();' – Redsandro