1

I am facing a bug that I cant use the .slice() method of javascript in react, basically I call the slice() method inside a function in class-based component, and the function in which I put the slice is passed to 2 levels down child component and triggered from there onClick event but the issue is that the slice method is not doing its work of removing element it just consoles the same array, here I show you the code in simple concept,

useSlice = () => {
  let arr = ['a', 'b', 'c'];
  console.log(arr.slice(1, 1));
}

useSlice()

this code print the same values of the array in the console instead of displaying the modified array. What to do ???

3
  • Post your whole code. Commented Sep 9, 2020 at 4:29
  • It is difficult from information to debug thhis pls post relevant code Commented Sep 9, 2020 at 4:29
  • Please read the documentaion Commented Sep 9, 2020 at 4:47

2 Answers 2

5

You should read more detail about how splice work at: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice

The second param in slice is end index (exclusive). So, if you arr.slice(1,1): mean slice from index 1 to index just before 1 will always return empty array.

By the way, if you want to remove element. You should use 'splice' instead.

Sign up to request clarification or add additional context in comments.

Comments

2

arr.slice(1,1) returns [], as it should. You're starting at element 1 and ending at element 1, which is zero elements. This is effectively range 1-0, which you can't do.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.