最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

javascript - Why array push not working in my function? - Stack Overflow

matteradmin8PV0评论

I've made a simple function that adds a value to the array in javascript and then returns them.

What I can't return is the added value. What am I doing wrong?

It returns "c" instead of 3.

Fiddle /

Code:

function test(a, b, c) {
  var array = [a, b];
  array.push('c');
  alert(array);
}
test(1, 2, 3);

I've made a simple function that adds a value to the array in javascript and then returns them.

What I can't return is the added value. What am I doing wrong?

It returns "c" instead of 3.

Fiddle http://jsfiddle/0rapj8y8/2/

Code:

function test(a, b, c) {
  var array = [a, b];
  array.push('c');
  alert(array);
}
test(1, 2, 3);

Share Improve this question asked Oct 1, 2015 at 8:02 Ionut NeculaIonut Necula 11.5k4 gold badges49 silver badges72 bronze badges 3
  • 2 array.push(c); - no '' - when you enclose c in quotes in it is treated as the string literal c, since you want to push the value referred by the variable c don't enclose it – Arun P Johny Commented Oct 1, 2015 at 8:04
  • Hmm..my mistake. Thanks. – Ionut Necula Commented Oct 1, 2015 at 8:05
  • I've made it a string. Saw that now. Thank you. – Ionut Necula Commented Oct 1, 2015 at 8:06
Add a ment  | 

3 Answers 3

Reset to default 4

Very basic language syntax issue. Why do you quote a variable name?

array.push('c');  

That is a character c, not your variable c

array.push(c);  // that is now your variable c

Fiddle

Remove the quotes

function test(a, b, c) {
  var array = [a, b];
  array.push(c);
  alert(array);
}
test(1, 2, 3);

Remove Quote in push fuction as follows

function test(a, b, c) {
  var array = [a, b];
  array.push(c);
  alert(array);
}
test(1, 2, 3);

Post a comment

comment list (0)

  1. No comments so far