0

Something magical happen. I'm stuck. How to push string into array?

const createParamForm = (paramsForms, setParamsForms) => {
  console.log('TCL: createParamForm -> paramsForms', paramsForms)
  const id = `f${(+new Date()).toString(16)}`
  console.log('TCL: createParamForm -> id', id)
  const paramsFormsClone = cloneDeep(paramsForms)
  console.log('TCL: createParamForm -> paramsFormsClone', paramsFormsClone)
  console.log(paramsFormsClone.push('banan'))
  // setParamsForms(newParamsForms)
}

The logs:

enter image description here

Why i'm getting 1 instead of ['banan'] ??

WhoIsDT
  • 695
  • 2
  • 9
  • 27
  • 2
    Because the _return value_ of `push` is the new length of the array, not the array itself. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push – mbojko Feb 05 '20 at 10:13

4 Answers4

2

Array push returns the new length of the array, not the actual values in it. Your'e fine.

MorKadosh
  • 5,846
  • 3
  • 25
  • 37
1

console.log(paramsFormsClone.push('banan')); statement return length of array.

Please check by using console.log(paramsFormsClone);

1

Issue: Instead of logging paramsFormsClone, you have been logged operation paramsFormsClone.push('banan') which returns the new length of the array(1 here).

You have to change the code as:

const createParamForm = (paramsForms, setParamsForms) => {
  console.log('TCL: createParamForm -> paramsForms', paramsForms)
  const id = `f${(+new Date()).toString(16)}`
  console.log('TCL: createParamForm -> id', id)
  const paramsFormsClone = cloneDeep(paramsForms)
  console.log('TCL: createParamForm -> paramsFormsClone', paramsFormsClone)
  paramsFormsClone.push('banan')
  console.log(paramsFormsClone)
  // setParamsForms(newParamsForms)
}
1

As push() returns the new length of the array after changes hence in your case it returns 1.