如何在没有分隔符的情况下拆分字符串?

sup*_*dr1 0 javascript

我有字符串"513".我需要数组["5","1","3"].我的解决方案:

function nextBigger(num){
    let numStr = '' + num;
  let numArr = [];

  for(let i = 0; i < numStr.length; ++i) {
    numArr.push(numStr[i]);
  }

  console.log(numArr);
}

nextBigger(513);
Run Code Online (Sandbox Code Playgroud)

但是这个解决方案很大且多余.我需要更短的解决方案

Nin*_*olz 7

使用ES6,您可以使用带有可迭代的扩展语法...并迭代单个项目.

或者只是采取Array.from几乎相同(甚至更多)的力量.

const getCharacters1 = string => [...string];
const getCharacters2 = string => Array.from(string);

console.log(getCharacters1('513'));
console.log(getCharacters2('513'));
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)


Sco*_*cus 6

您可以.split()使用空字符串作为分隔符.这将在每个字符处拆分字符串:

function nextBigger(num){
  console.log(num.toString().split(""));
}

nextBigger(513);
Run Code Online (Sandbox Code Playgroud)