Hello all,
I’ve got the following array and like to add new values to it.
arr = ["A","B","C","D"];
Let’s say I’d like to add the value "John"
to "B"
.
I’ve tried the following but without success
arr[1].push(["John"]);
Any ideas?
Hello all,
I’ve got the following array and like to add new values to it.
arr = ["A","B","C","D"];
Let’s say I’d like to add the value "John"
to "B"
.
I’ve tried the following but without success
arr[1].push(["John"]);
Any ideas?
Hi Ethannn,
arr[1] is currently the string “B”. Are you saying that you want to concatenate the two strings, so that the value is “BJohn”? Or you want to replace the string with a nested array containing both strings (i.e. ["B", "John"]
)?
Push is an array method that adds a new value to the end of the array. What you’re doing here is retrieving the value at index 1 (which is a string) and trying to call push
on it, which fails because strings have no push
method.
If you started off with a multidimensional array, then you could use push:
var arr = [["A"],["B"],["C"],["D"]];
arr[1].push("John");
// arr is now [["A"],["B", "John"],["C"],["D"]]
Note that we’re pushing a string, not a string wrapped in an array as in your original example, otherwise we’d end up with [["A"],["B", ["John"]],["C"],["D"]]
That worked!
Thank you for sharing your knowledge!
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.