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;
});我使用上面的代码来删除未定义的元素,但是它会破坏我的索引/键值。
或者一开始有什么办法可以避免呢?
发布于 2017-11-29 08:02:44
数组是索引数据结构。因此,在使用它们时,最好保持该结构,否则就没有使用数组的必要。对于用例,可以使用Map()还是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)
}
发布于 2017-11-29 07:47:40
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(),并使用map.size获取大小。
发布于 2017-11-29 09:49:00
我只想用一个对象来存储你的值。
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]);
}https://stackoverflow.com/questions/47547406
复制相似问题