从数组中删除空字符串,同时保持索引的记录与非空字符串
问题描述:
可以说我有一个数组如下:
Lets say I have an array as follows:
"I", "am", "", "still", "here", "", "man"
从这个我想产生以下两个数组:
and from this I wish to produce the following two arrays:
"I", "am", "still", "here", "man"
0, 1, 3, 4, 6
因此,如果没有空字符串的数组,也可与非空字符串的数组索引的阵列。什么是生产从第一这两个数组的一个很好的方式?
So, an array without the empty strings, but also an array with the array indexes of the non empty strings. What would be a nice way of producing these two arrays from the first?
更新:
我需要数组的第一完好,两个阵列后产生。
I need the first array intact, after the two arrays are produced.
答
遍历数组,并检查每个元素都是空的。如果它没有,添加它的位置给一个数组并将其值改为另一个数组:
Loop through the array and check if each element is empty. If it's not, add its position to one array and its value to another array:
var elems, positions
for (var i = 0; i < arr.length; i++){
if (arr[i] != ""){
elems.push(arr[i])
positions.push(i)
}
}
编辑:这会留下3阵列(原件,元素,位置)。如果你宁愿只需要修改原来的使用 arr.filter()