Javascript: get the length of a string without the correct length and using fragment

I know this is weird! But why does this not work?

function getStringLength(string) {

  // see how many substrings > 0 can be built
  // log that number & return

  var subString = string.slice();
  var counter = 0;

  while (subString !== '') {
    counter++;
    subString = subString.slice(counter);
  }

  return counter;
}

var output = getStringLength('hello');

console.log(output); // --> expecting 5, but getting 3 (??)

I really want to do this with a piece! The initial task was not to use the length property, and I figured it out that works great:

function getStringLength(string) {

  var long = 0;

  while (string[long] !== undefined) {
    long++;
  }

  return long;
}
+4
source share
4 answers

you changed your line, this should work for you

function getStringLength(string) {

  // see how many substrings > 0 can be built
  // log that number & return

  var subString = string.slice();
  var counter = 0;

  while (subString !== '') {
    counter++;
    subString = subString.slice(1);
  }

  return counter;
}

var output = getStringLength('hello');

console.log(output); // 5
Run codeHide result

The main difference was what I was doing

subString = subString.slice(1);

instead

subString = subString.slice(counter);

which always reduced length by 1

+6
source

substring.slice(counter) 1 . 2 . 1 , . substring.slice(1), string.slice(counter)

function getStringLength(string) {

  // see how many substrings > 0 can be built
  // log that number & return

  var subString = string.slice();
  var counter = 0;

  while (subString !== '') {
    counter++;
    subString = substring.slice(1);
  }

  return counter;
}

var output = getStringLength('hello');

console.log(output); 
Hide result
+4

To achieve the expected result, use the option below.

function getStringLength(arr){
  return arr.lastIndexOf(arr.slice(-1))+1
}

var output = getStringLength('hello');
console.log(output);

https://codepen.io/nagasai/pen/gGPWEE?editors=1111

Option2: As an array type is an object, below option works too

function getStringLength(arr){
  return Object.keys(arr).pop()*1 + 1
}

var output = getStringLength('hello');
console.log(output);

https://codepen.io/nagasai/pen/PJZmgg?editors=1111

Check the updated options below to handle blanks and numbers https://codepen.io/nagasai/pen/GMoQgy?editors=1111
https://codepen.io/nagasai/pen/YrweWr?editors=1111

+1
source

Perhaps a slightly shorter answer:

function getStringLength(string) {
  var counter = 0;
  while (string.slice(counter)) {
    counter++;
  }

  return counter;
}

var outputHello = getStringLength('hello');
console.log(outputHello); // 5

var outputEmpty = getStringLength('');
console.log(outputEmpty); // 0
Run codeHide result
0
source

Source: https://habr.com/ru/post/1685907/


All Articles