js string loop All In One


js string loop All In One

String to Array

  1. Array.from
const str = 'ABC';

for (const item of Array.from(str)) {
  console.log(item);
}

  1. Array.prototype.split
const str = 'ABC';

for (const item of str.split('')) {
  console.log(item);
}

  1. [...string]

destructuring assignment

const str = 'ABC';

for (const item of [...str]) {
  console.log(item);
}

  1. Object.assign

const str = 'ABC';

for (const item of Object.assign([], str)) {
  console.log(item);
}


??? JSON.parse ?

conststr = 'abc';

JSON.parse("[" + str + "]");

const str = 'a,b,c';

JSON.parse("[" + str + "]");

for

  1. for...of


const str = 'ABC';

for (const item of str) {
  console.log(item);
}

  1. for await...of
const str = 'ABC';

for await (const item of str) {
  console.log(item);
}
  1. for...in
const str = 'ABC';

for (const index in str) {
  console.log(str[index], index);
}

  1. for

const str = 'ABC';

for (let i = 0; i < str.length; i++) {
  console.log(str[i], i);
}


refs

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String


Flag Counter

?xgqfrms 2012-2020

www.cnblogs.com/xgqfrms 发布文章使用:只允许注册用户才可以访问!

原创文章,版权所有??xgqfrms, 禁止转载 ???,侵权必究??!