javascript - 如何将数组转为数字?

标签 javascript arrays

var beasts = 'ant 222, bison, ant 333, ant 555, goose 234';

function countAllBeasts(antMany) {

  var OrigString = antMany.split(', ');

  for (var i = 0; i < OrigString.length; i++){
    var justAnt = OrigString[i];
   ;
    if (OrigString.startsWith('CJ') === true){
      (justAnt.length);

    }
  }
  var forLoop = justAnt[i];
  console.log(forLoop);

  return justAnt;
};

更新:我仍然想使用 for 循环,因为该部分需要它,并且它比其他方法更简单。希望进行最少的更改以提供字符串中 ant xxx 的数量,该数量是在分割、在 for 循环中运行并使用startsWith 按 ant 排序后产生的。我知道还有其他方法,但我正在寻找最简单的。以前不太清楚,现在清楚了。

最佳答案

使用正则表达式,您只需一行代码即可完成此任务。

// This will return 4 matches (4 commas) + 1 = count of blocks separated by comma.
new RegExp("\,", "g") 

let count = 'ant 222, bison, ant 333, ant 555, goose 234'.match(new RegExp("\,", "g")).length + 1;
console.log(count);

根据您的方法: 使用基本的for循环

function countAllBeasts(antMany) {
  var origString = antMany.split(', ');
  var ants = [];
  
  for (var i = 0; i < origString.length; i++) {
    if (origString[i].startsWith('ant'))
       ants.push(origString[i]);
  }
  
  return ants;
}

var beasts = 'ant 222, bison, ant 333, ant 555, goose 234';
console.log(countAllBeasts(beasts));

您可以使用函数filter来实现这一点

function countAllBeasts(antMany) {
  var origString = antMany.split(', ');
  var ants = origString.filter((block) => block.trim().startsWith('ant'));

  return ants;
}

var beasts = 'ant 222, bison, ant 333, ant 555, goose 234';
console.log(countAllBeasts(beasts));

关于javascript - 如何将数组转为数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48477960/

相关文章:

ios - 数组数据在 swift 4 的 TableView 中重复

Javascript 在按钮单击时设置 cookie 过期时间

javascript - 如何设置尚未定义的元素的属性并动态创建它?

php - 在 PHP 中将二维数组转换为 JSON

ruby - 如何检查数组中是否设置了 nil?

php - 访问多个 JSON

python - 将文件元素读入 3 个不同的数组

javascript - 仅适用于 Javascript 智能手机的离线应用程序

javascript - 创建新的 Mongodb 文档与推送到文档数组

javascript - 无法使用removeChild删除我的2个INPUT字段