i have this loop.
now, in a[i] im putting name of college, for example UCLA.
in temp i have the name of the player i want to insert into the a[i][p]
When im looking at temp
im seeing the name that i actualy wants to insert, but them im
doing this line a[i][p] = temp;
im seeing in a[0][0]='U',
why?
var a = [[]];
var p = 0;
var temp;
for (var i = 0; i < uniq.length; i ) {
a[i] = uniq[i];
for (var k = 0; k < data.players.length; k ) {
if (uniq[i] == data.players[k].college)
{
temp = data.players[k].name
a[i][p] = temp;
p ;
}
}
p = 0;
}
console.log(a[0][0])
CodePudding user response:
The answer is:
- first you put
UCLA
as the value ofa[0]
now your array looks like this:
console.log(a[0]) // expected "UCLA"
string
s in JavaScript can be iterated over - this means (roughly), that you can geta[0][0]
in this case: the first item of the first item of thea
array - and that is "the first character of the string at the first index ina
"
console.log(a[0][0]) // expected: "U", if a[0] is "UCLA"
const a = []
a[0] = "UCLA"
console.log(a)
console.log(a[0])
console.log(a[0][0])
You need to do it a bit differently (this could be one approach, but there could be more):
const a = {} // this is an object, not an array!
a["UCLA"] = "name of tthe player"
console.log(a)
console.log(a["UCLA"])
Or, if you need an array, then you could do:
const a = []
a[0] = { uni: "UCLA", player: [] }
a[0].player[0] = "name of the player"
console.log(a)
CodePudding user response:
when indexing JavaScript strings they behave like arrays and you actually get a 1 letter string with the character on the index you requested
for example:
var dummy = "house";
console.log(dummy[1]);
//this is going to return o (character in index 1 of house)
note that when indexing a string you are going to get another string and not a char like in other languages,
to achieve what you are trying to do you can use a dictionary like this:
var schools = {};
for (var i = 0; i < uniq.length; i ) {
schools[uniq[i]] = [];
for (var k = 0; k < data.players.length; k ) {
if (uniq[i] == data.players[k].college)
{
schools[uniq[i]].push(data.players[k].name);
}
}
}
at the end of this you can access schools either by indexing, by string key (college name) or with a simple foreach
schools[1]; //this is gonna give ["firstname","secondname","etc"] (player names of the second school)
schools["UCLA"]; //this is gonna give ["firstname","secondname","etc"] (player names of UCLA school)