Reputation: 355
I'm getting an unexpected identifier error with this line of code: var player[data[x].split("|",1)] = data[x].split("|")[1];
The response data is in this format:
Mike Trout|0\nRyan Braun|0\n...
Here is the full JS function:
function updateChance(round, pickNumber)
{
$.ajax({
type: "GET",
data: {round: round, pickNumber: pickNumber},
url: "./lib/updatechance.php",
dataType: "html",
async: false,
success: function(response)
{
var data = response.split("\n");
for (var x=0; data.length; x++)
{
var player[data[x].split("|",1)] = data[x].split("|")[1];
}
for (var r = 1; r < $('#battersTable').rows.length; r++){
//do something with player
}
}
});
}
Upvotes: 0
Views: 755
Reputation: 207521
Look what you did here
.split("|",1) //wrong
and
.split("|")[1] //right
another issue, you have var
with the bracket notation, not going to happen.
var player[data[x].split("|",1)] <-- var, should not be there
And the for loop is missing a check so that is going to run infinite.
for (var x=0; data.length; x++) <-- data.length what?
Why are you splitting twice? Twice the effort, do it once
for (var x=0; x<data.length; x++) {
var info = data[x].split("|");
player[info[0]] = info[1];
}
If player
is not defined globally, you will need to define it before the loop.
Upvotes: 2
Reputation: 35920
You can't access an object indexer in the same statement where you declare the variable. The split
function also only takes a single argument and returns an indexable array. So this:
for (var x=0; data.length; x++) {
var player[data[x].split("|",1)] = data[x].split("|")[1];
}
Should be:
var player = {};
for (var x=0; x < data.length; x++) {
var value = data[x].split("|")[1];
player[value] = value;
}
Also storing the result of the split operation in an intermediate variable, and fixing the loop syntax issues which would've caused the loop to crash at the end anyway, had the syntax error not prevented the code from running.
All in all, since you had quite a few syntax problems, I would recommend running your code through a linter such as jshint. It'll give you a detailed error report of the problems.
Upvotes: 1
Reputation: 16255
I'm guessing you want to do this:
var player = {};
for (var x=0; data.length; x++) {
var flds = data[x].split("|");
player[flds[0]] = flds[1];
}
Upvotes: 1
Reputation: 114529
in
var player[data[x].split("|",1)] = data[x].split("|")[1];
the keyword var
doesn't make sense. You need it only to declare a local variable, what follows here is instead just an assignment.
There are other issues (see other answers and comments) but this is actually the syntax error that the borwser is reporting.
Upvotes: 1