Javascript - 重新索引数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4759745/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:57:40  来源:igfitidea点击:

Javascript - Reindexing an array

javascriptarraysserialization

提问by borayeris

Hereis my example. Can you tell me how can I make the array have consecutive keys

是我的例子。你能告诉我如何让数组有连续的键吗

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

when I have

当我有

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

Editor's note:The asker wants to reindex his array.

编者按:提问者想要重新索引他的数组。

采纳答案by Exelian

If you don't mind using javascript 1.6: (note: this code uses the jQUery library)

如果您不介意使用 javascript 1.6:(注意:此代码使用 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);
});

filter prototype:

过滤器原型:

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

回答by Redsandro

Array.prototype.filter()is not executed on deleted or previously undefined items. So you can simply do:

Array.prototype.filter()不会对已删除或以前未定义的项目执行。所以你可以简单地做:

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

..in order to re-index your array.

..为了重新索引你的数组。

Or ES6:

或 ES6:

testArray.filter(val => val)

回答by Arron

Super simple function:

超级简单的功能:

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

Note: this will blow away any custom keys. the result will always be numerically indexed. you could add in checks for if it's an array or not but i tend to just not use functions i build other than they are intended to be used. you can also start the index higher if you like:

注意:这将吹走任何自定义键。结果将始终以数字索引。您可以添加检查它是否是数组,但我倾向于不使用我构建的函数,而不是打算使用的函数。如果您愿意,也可以将索引设置得更高:

testArray = reindex_array_keys(testArray, 3);

which will produce 3 'undefined' items at the beginning of the array. you can then add to it later but i think it would be better to do testArray.unshift('newValue')first then reindex personally.

这将在数​​组的开头产生 3 个“未定义”项。你可以稍后再添加它,但我认为最好先做testArray.unshift('newValue')然后亲自重新索引。

have fun

玩得开心

回答by Nina Scholz

You could filter the array by using a callback which returns trueor other truthyvalue, because Array#filteromits sparse elements.

您可以使用返回true或其他真实值的回调来过滤数组,因为Array#filter省略了稀疏元素。

If Booleanis taken, the result filters not only sparse items, but items which have a falsyvalue. To prevent this, take a callback which returns truefor every element.

如果Boolean采用,结果不仅会过滤稀疏项,还会过滤具有虚假值的项。为了防止这种情况,采取一个true为每个元素返回的回调。

array.filter(_ => true);

var array = [];

array[10] = 0;
array[20] = 0;
array[30] = 0;

console.log(array.filter(_ => true).join('|'))

回答by capdragon

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

回答by elasticrash

you mean without the commas? if so just do this var testString = testArray.join("");or you can add any char you want between.

你的意思是没有逗号?如果是这样,就这样做,var testString = testArray.join("");或者您可以在两者之间添加任何您想要的字符。

回答by Wazy

TryThis

试试这个

var testArray=testArray.join(" ");