2011-01-21 16 views
12

Here es mi ejemplo. ¿Me puede decir cómo puedo hacer que la matriz tiene llaves consecutivasJavascript - Reindexando una matriz

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

cuando tengo

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

Nota del editor: El autor de la pregunta quiere indexar su matriz.

+1

hacer lo que la matriz? – WarrenFaith

+1

Probablemente quiera reindexar la matriz, a juzgar por su violín. –

+0

@warren; en mi ejemplo, las teclas de matriz son 3, 7, 13. Cuando las serialicé, se convirtió en ",,, qwerty ,,,, asdfgh ,,,,,, zxcvbn". Lo que quiero es "qwerty, asdfgh, zxcvbn". – borayeris

Respuesta

8

Si no les importa usar Javascript a 1,6: (nota: este código se utiliza la librería 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

Simplemente copié su código de JsFiddle, pero pondré una nueva versión para otro usuario. Gracias por el aviso. – Exelian

+0

Gracias Exalian. – borayeris

0

que quiere decir sin las comas? de ser así, solo haga esto var testString = testArray.join(""); o puede agregar cualquier char que desee.

+0

Lo que necesito es volver a indexar la matriz. No esta. – borayeris

+0

siempre puede simplemente unirse a la matriz y luego volver a encenderla con un cierto delimitador. Tal vez no es tan profesional, pero sus 2 líneas de código. – elasticrash

+0

unir y volver a dividir no funcionará si los elementos de la matriz son objetos, por ejemplo –

0

Trate Este

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

Lo que necesito es volver a indexar la matriz. No esta. – 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

función Super simple:

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: esto va a soplar las teclas personalizables. el resultado siempre estará indexado numéricamente. podrías agregar cheques para si es una matriz o no, pero tiendo a no usar funciones que construyo aparte de las que están destinadas a ser usadas. también puede iniciar el índice más alto si te gusta:

testArray = reindex_array_keys(testArray, 3); 

que producirá artículos 3 'definido' al comienzo de la matriz. luego puede agregarlo, pero creo que sería mejor hacer primero testArray.unshift('newValue') y reindexar personalmente.

divertirse

+0

Uncaught ReferenceError: i no está definido – fdrv

20

Array.prototype.filter() no se ejecuta en los artículos indefinidos o eliminados previamente. Así que usted puede simplemente hacer:

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

..en fin de volver a indexar su matriz.

O ES6:

testArray.filter(val => val) 
+1

Ding ding ding - la respuesta más corta, y no implica el uso de operadores de comparación sueltos. – aendrew

+2

Tenga en cuenta que devolverá una nueva matriz sin afectar 'testArray'. Es posible que desee redefinirlo: 'testArray = testArray.filter (val => val);' – pmrotule

+0

@pmrotule si desea mantenerlo, sí. Siguiendo el ejemplo en la pregunta, el más corto sería 'var testString = testArray.filter (val => val) .join();' – Redsandro

Cuestiones relacionadas