简体   繁体   English

Javascript 在特定索引的数组中拆分字符串

[英]Javascript split strings in array on specific index

I have this array of strings.我有这个字符串数组。

const numbersArray = ['1000','10000','100000']

My goal is to split each one of them on specific index for example: output of 1000 should be 1,000 and etc...我的目标是在特定索引上拆分它们中的每一个,例如:output of 1000 应该是1,000等等...

Here is what i have right now:这是我现在拥有的:

  const splitArrayHandler = (arr) =>{
  for (let i = 0; i < arr.length; i++) {
    let indexOfSymbol = Math.round(arr[i].length / 3)
    return splitAtIndex(arr[i],indexOfSymbol)
  }
}

const splitAtIndex = (value,index) => {
  return value.substring(0,index) + ',' + value.substring(index)
}

splitArrayHandler(numbersArray)

The first function splitArrayHandler loops through my array,finds specific index of the symbol in the string and then function splitAtIndex does the rest of the hard work.第一个 function splitArrayHandler循环遍历我的数组,在字符串中找到符号的特定索引,然后 function splitAtIndex执行 rest 的艰苦工作。

The problem is only first element of the string is passing to the splitAtIndex function and I dont understand why.问题只是字符串的第一个元素传递给splitAtIndex function 我不明白为什么。 any suggestions please?请问有什么建议吗?

 const numbersArray = ['1000','10000','100000'] const splitArrayHandler = (arr) =>{ for (let i = 0; i < arr.length; i++) { let indexOfSymbol = Math.round(arr[i].length / 3) return splitAtIndex(arr[i],indexOfSymbol) } } const splitAtIndex = (value,index) => { return value.substring(0,index) + ',' + value.substring(index) } splitArrayHandler(numbersArray)

Use Intl.NumberFormat for the job.对作业使用Intl.NumberFormat No need for string parsing / manipulating:无需字符串解析/操作:

 const numbersArray = ['1000', '10000', '100000', '654654686156', '1000.66', '10e14', '0xFFFF']; const format = new Intl.NumberFormat('en-US').format; const formattedNumbers = numbersArray.map(Number).map(format); console.log(formattedNumbers);

You might use regular expression and map function (though there is no real difference between map and hard coded loop)您可以使用正则表达式和map function (尽管 map 和硬编码循环之间没有真正的区别)

const numbersArray = ['1000','10000','100000']
function addComa(x) {
    return x.replace(/\B(?=(\d{3})+(?!\d))/g, ',')
}
const resolved = numbersArray.map(addComma)
console.log(resolved) // ['1,000','10,000','100,000']

You are breaking the loop by returning the splitAtIndex function.您通过返回 splitAtIndex function 来打破循环。 Create another array and push the results to it.创建另一个数组并将结果推送给它。

const splitArrayHandler = (arr) =>{
  let arr2 = []
  for (let i = 0; i < arr.length; i++) {
    let indexOfSymbol = Math.round(arr[i].length / 3)
    arr2.push(splitAtIndex(arr[i],indexOfSymbol))
  }
  return arr2
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM