1

I am getting error push() is not a function while pushing element in >array? giving me error lik arry.push is not a function

 var abc=["get","get","get","get","get","get","get","get","get",];
 
 for(i=0;i<abc.length;i++){
 let a=abc[i].push("mate");
 
 console.log(abc);
 }
asked Mar 22, 2022 at 6:36
3
  • read more about how .push works. Commented Mar 22, 2022 at 6:42
  • abc is an array, abc[i] is an element of the array, in your case a string. strings don't have a push method ... Commented Mar 22, 2022 at 6:43
  • Can you give me any alternative to replace all element of array with new one using for loop? Commented Mar 22, 2022 at 11:31

4 Answers 4

1

You should delete the [i] in abc[i].push() because abc[i] is string, but the .push() method works for arrays. Therefore you should use abc.push() instead of abc[i].push().

Nikolaj Dam Larsen
5,7246 gold badges38 silver badges46 bronze badges
answered Mar 22, 2022 at 6:53
Sign up to request clarification or add additional context in comments.

Comments

1

When you do abc[i].push(), you're actually calling .push() on the string at index i, not the array. Strings do not have the function .push() which is where your error is coming from

Instead try the following:

abc.push("mate");
answered Mar 22, 2022 at 6:42

Comments

0

To push elements in an array, simply use the Array.prototype.push method.

var abc = ["get", "get", "get", "get", "get", "get", "get", "get", "get"]
abc.push("mate")

Read more about how push works here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

The origin point of your error is that, you are accessing each array elements which are strings and trying to use the push() method on those.

answered Mar 22, 2022 at 6:45

Comments

0

The .push() method is for array only. In the loop, you're using abc[i] which means you're accessing each element of the array, not the whole array..

The above method works to add element to end of the array. So use abc.push()

answered Jul 18, 2023 at 7:47

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.