算空数组

问题描述 投票:0回答:5
我需要计算字符串的字母,我不知道如何计算一个空阵列

const regex = /[\[\]]/gi; const a = str.replaceAll(regex, ' ').trim().split(" ") const arr = [] const arr2 = [] let newArr for(let i = 0; i < a.length; i++) { if (a[i].length === 0) { arr2.push(0) } if (a[i].length !== 0) { arr.push(a[i].length) } } newArr = arr.concat(arr2) if (newArr.includes(0)) { newArr.pop() } return newArr.join(", ")
我必须得到:
[汤姆] []  - > 3,0
但是我得到3个没有零

javascript arrays
5个回答
3
投票
(\[[a-zA-Z]*\])*

.

I将删除第一个

[

和最后一个

]
。然后,我将字符串按
][

const str = '[Tom][]'; const substrs = str.substring(1, str.length - 1).split(']['); const lengths = substrs.map(str => str.length); console.log(lengths.join(', '));

使用ES6您可以以更简单的方式进行操作

2
投票

const str = '[Tom][]'; const count = str.match(/\[(.*?)\]/g) .map(x => x.slice(1, -1)) .map(x => x.length) .join(', '); console.log(count);

您可以通过数组操作来实现这一目标:


1
投票

function f(str) { return str.split("[").filter(item => item.length).map(item => item.substring(0, item.length - 1).length).join(", "); } console.log(f("[tom][]"));


解释

str.split("[")

str
    用作分离器分为代表代币
  1. 的不同字符串
    [
    在上一个步骤中所拥有的数组中,将忽略我们空字符串的所有令牌
    .filter(item => item.length)
  2. 将令牌字符串(例如
  3. .map(item -> item.substring(0, item.length - 1))
    tom]
  4. 都考虑到,在没有闭合的情况下为它们获得子字符串,并分别计算结果的
  5. ]
    ,分别具有3和0实际令牌
    
    ]
    将3和0的值分别转换为单个字符串,将项目与
    length
    分开,因此它将导致
    .join(", ")
    
        
  6. , 
    带有此正则的给定字符串:
  7. 3, 0

1
投票
.split()
  1. 注意:右支架

    /\[(.*?\])/

    用作占位符

    next,

    ["", "Tom]", "", "]", ""]

    数组通过分配一个空数组作为累加器的初始值
    "]"

    .reduce()
  2. ,然后跳过0的索引,甚至所有编号索引:
    cnt

    在任何奇数索引中,删除第一个字符,然后将字符串的
  3. .reduce((cnt, seg) => { ... }, []);
  4. 添加到数组

    if (idx % 2 === 0) return cnt;

    .length
  5. 恢复:
  6. cnt

    
    
    最终,

    cnt.push(seg.slice(1).length); return cnt;
    数字数组成字符串。
    

  7. [3, 0]

    
    

使用
.join(", ")
查找在
const charCounts = (str) => {
  return str
  .split(/\[(.*?\])/)
  .reduce((cnt, seg) => {
    if (idx % 2 === 0) return cnt;
    cnt.push(seg.slice(1).length);
    return cnt;
  }, []).join(", ");
};             
  
console.log(charCounts("[Tom][]"));
  
之间的所有捕获组,并且不包含
String.matchAll()
。将迭代器转换为使用

[]

的一系列条目,然后从第二项进入条目:

1
投票


]


    

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.