使用子字符串javascript过滤列表?

时间:2015-09-30 02:46:52

标签: javascript

var ctr;
var lst = ["", "xml", "w1", "w2"];
var ids = [];
ctr = 0;
for (y = 0; y < lst.length; y++) {
    if (lst[y].substring(0, 1) === "w") {
        ids[y] = lst[y];
        ctr = ctr + 1;
    }
}
console.log([ids, ctr]);

输出:[[undefined, undefined, 'w1','w2'], 2]
预期输出:[['w1','w2'],2]

我做错了什么?计数器返回了我预期的数字,但为什么我的列表中有2个未定义?为什么会这样?

5 个答案:

答案 0 :(得分:5)

您需要使用ids.push(lst[y]);而不是ids[y] = lst[y];,否则您将在随机索引处为ids数组赋值 - 即缺少某些索引值。

在你的代码中,值在索引2和3处分配,缺少索引0和1导致所述输出,这是因为你没有在所有迭代中为ids赋值 - 你正在跳过一些基于的迭代条件

答案 1 :(得分:4)

您可以使用过滤器来获取所需的项目,也可以使用输出数组长度来了解过滤原始数组后的项目数。

var newArr = ["", "xml", "w1", "w2"].filter(function(x) {
  x.substring(0, 1) === 'w');
};

console.log([newArr, newArr.length]);    // [["w1", "w2"], 2]

答案 2 :(得分:2)

var lst = ["", "xml", "w1", "w2"];

var result = lst.reduce(function (x, y) {
  if (y.substring(0, 1) === 'w') {
    x[0] || (x[0] = []);
    x[0].push(y);
    x[1]++ || (x[1] = 1);
  }
  return x;
}, []);

console.log(result) // [["w1","w2"],2]

结果将与要求相同,这里有趣的是我使用空合并符号|| more info about it here

@FelixKing更改累加器

的建议
lst.reduce(function (x, y) {
  if (y.substring(0, 1) === 'w') {
    x[0].push(y);
    x[1]++;
  }
  return x;
}, [[], 0]);

答案 3 :(得分:1)

使用现有的js,尝试在ctr语句中替换y if

var ctr;
var lst = ["", "xml", "w1", "w2"];
var ids = [];
ctr = 0;
for (y = 0; y < lst.length; y++) {
  if (lst[y].substring(0, 1) === "w") {
    ids[ctr] = lst[y];
    ctr = ctr + 1;
  } 
}

console.log([ids, ctr]);

或者,使用Array.prototype.toString()String.prototype.match()

var lst = ["", "xml", "w1", "w2"]
, ids = lst.toString().match(/w./g);
console.log(ids);

答案 4 :(得分:1)

如果您想采用不同的方法,使用reduce也可以:

var res = lst.reduce(function(prevVal, curVal){
    if (curVal.substring(0, 1) === "w") {
        prevVal[0].push(curVal);
        prevVal[1] = prevVal[1] + 1;
    }
    return prevVal;
}, [[], 0]);

console.log(res); //--> [['w1', 'w2'], 2]

我推荐它只是因为尽可能避免使用for循环会产生更多可维护的代码,尤其是在Javascript中,for循环条件中使用的变量仍然是父作用域的成员(即它们可以在整个包含中访问)函数,给定值为undefined,直到在for循环中给出初始化值。)

此外,它还可以防止您不得不在头脑中处理索引值,而是专注于循环实际执行的操作。

(我上面的例子肯定会更干净,但它应该给你一个想法)