过滤列表与子字符串javascript

Filter list with substring javascript?

本文关键字:字符串 javascript 列表 过滤      更新时间:2023-09-26
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个未定义?为什么会发生这种情况?

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

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

您可以使用过滤器来获取您想要的项目,或者使用输出数组长度来知道过滤原始数组后您有多少项。

var newArr = ["", "xml", "w1", "w2"].filter(function(x) {
  x.substring(0, 1) === 'w');
};
console.log([newArr, newArr.length]);    // [["w1", "w2"], 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]

结果将与要求相同,有趣的是这里我使用空合并符号||更多信息在这里

@FelixKing建议更改累加器

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

如果您想采用不同的方法,使用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循环条件中使用的变量本身仍然是父作用域的成员(即它们在整个包含函数中都可以访问,在for循环中给出初始化值之前,它们的值是未定义的)。

而且,它还可以防止您在头脑中反复考虑索引值,而是专注于循环实际在做什么。

(我上面的例子肯定可以更简洁,但它应该给你一个想法)

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

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