JavaScript Array创建空元素

时间:2017-11-29 07:39:56

标签: javascript arrays angularjs



var arr = [];
console.log(arr);
console.log("Length: " + arr.length);
arr[1] = [{},{}];
console.log(arr);
console.log("Length: " + arr.length);
arr[3] = [{},{}];
console.log(arr);
console.log("Length: " + arr.length);




因此,当我创建一个类似于上面的数组时,它会在其间提供空/未定义的元素。

我想在保留索引值的同时删除那些空/未定义的元素。

vm.eArray = vm.eArray.filter(function (arr) {
    return arr.length;
});

我使用上面的代码删除了未定义的元素,但它混淆了我的索引/键值。

或者有没有办法在第一时间避免它?

4 个答案:

答案 0 :(得分:2)



struct




您可以使用var arr = new Map(); console.log(arr); console.log("Length: " + arr.size); arr.set(1,[{},{}]); console.log(arr); console.log("Length: " + arr.size); arr.set(3,[{},{}]); console.log(arr); console.log("Length: " + arr.size);,并使用Map()获取尺寸。

答案 1 :(得分:2)

Array是索引数据结构。因此,在使用它们时,最好保留该结构,否则无法使用数组。对于您的用例,您可以使用Map()或Json元素数组。

  • 使用Map,索引(1,2,3)可以直接成为数组的键。
  • 另一个解决方案可能是使用Json元素数组,其中每个元素都有一个键和一个值

var myMap = new Map();
//to add the element with index 1
myMap.set(1, [{},{}]);

//to add the element with index 3
myMap.set(3, [{},{}]);

// you can iterate over them if you want like an array
console.log("with a map")
myMap.forEach((key, value) => console.log(key, value));

// using a Json object

var myObject = [];
myObject.push({id: 1, value:[{},{}]})
myObject.push({id: 3, value:[{},{}]})

//iterate over it, because it is still an array, but of Json element
console.log("with array of json")
for (element of myObject){
  console.log(element.id, element.value)
}

答案 2 :(得分:1)

我只想使用一个对象来存储你的值。

    var arr = {};
    console.log(arr);
    console.log("Length: " + Object.keys(arr).length);
    arr[1] = [{},{}];
    console.log(arr);
    console.log("Length: " + Object.keys(arr).length);
    arr[3] = [{},{}];
    console.log(arr);
    console.log("Length: " + Object.keys(arr).length);

    for (something in arr){
      console.log(arr[something]);
    }

答案 3 :(得分:0)

您在索引1处分配值arr[1] = arr[1] = [{},{}];。因此您正在跳过索引0.默认情况下,javascript会将undefined放在那里。

相关问题