Very simple thing I am trying to do in JS (assign the values of one array to another), but somehow the array bar's value doesn't seem affected at all.
The first thing I tried, of course, was simply bar = ar; -- didn't work, so I tried manually looping through... still doesn't work.
I don't grok the quirks of Javascript! Please help!!
var ar=["apple","banana","canaple"];
var bar;
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
And, here is the fiddle: http://jsfiddle.net/vGycZ/
(The above is a simplification. The actual array is multidimensional.)
-
check this : hardcode.nl/subcategory_1/…Pranay Rana– Pranay Rana2010年08月09日 07:25:28 +00:00Commented Aug 9, 2010 at 7:25
-
You could have spotted the syntax error ("arr" vs "ar") that was pointed out to you by using the Firebug plugin for Firefox. I'd go as far as to say you can't properly do Javascript development without it.Niels Bom– Niels Bom2010年08月09日 07:27:10 +00:00Commented Aug 9, 2010 at 7:27
-
i don't do much javascript - and tbh i never figured out how to use Firebug :( ... point a few good tutorials at me?ina– ina2010年08月09日 08:02:04 +00:00Commented Aug 9, 2010 at 8:02
8 Answers 8
Your code isn't working because you are not initializing bar:
var bar = [];
You also forgot to declare your i variable, which can be problematic, for example if the code is inside a function, i will end up being a global variable (always use var :).
But, you can avoid the loop, simply by using the slice method to create a copy of your first array:
var arr = ["apple","banana","canaple"];
var bar = arr.slice();
3 Comments
slice will shallow copy the array elements that are objects, could you provide a less simplified example, to see exactly what you want to achieve?copy-or-clone-javascript-array-object
var a = [ 'apple', 'orange', 'grape' ];
b = a.slice(0);
1 Comment
In ES6 you can use Array.from:
var ar = ["apple","banana","canaple"];
var bar = Array.from(ar);
alert(bar[1]); // alerts 'banana'
Comments
(削除) You have two problems: (削除ここまで)
First you need to initialize bar as an array:
var bar = [];
(削除) Then arr should be ar in here:
for(i=0;i<arr.length;i++){
(削除ここまで) Then you'll get alerted your banana :)
1 Comment
With ES6+ you can simply do this
const original = [1, 2, 3];
const newArray = [...original];
The documentation for spread syntax is here
To check, run this small code on dev console
const k = [1, 2];
const l = k
k === l
> true
const m = [...k]
m
> [1, 2]
k === m
> false
1 Comment
You have misspelled variable ar Try this
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
1 Comment
The problem probably here in the for loop statement:
for(i=0;i<ar.length;i++){
bar[i]=ar[i];
}
alert(ar[1]);
You need to fix to ar.length instead of arr.length. And it's better to initialize bar as: var bar = [].
Comments
In your code, the variable arr in the for loop is not the same as your original array ar: you have one too many r.