Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
625 views
in Technique[技术] by (71.8m points)

javascript - Using eval() - Uncaught SyntaxError: Unexpected identifier at pageLoad

first time using stackoverflow. :)

I am a beginner in JS trying to add values to a list of variables that may change based on the number of passengers variable. (ie. if numRiders = 4 I need to assign values to passenger1Name, passenger2Name, passenger3Name, passenger4Name)

I am trying to use eval inside a loop to do it:

for(i = 0; i<=numRiders; i++) {
    j = i+1
    var l ='var '
    var k = 'passenger'
    let nameJ = ride[i].passengerDetails.first + ' ' + ride[i].passengerDetails.last;
    console.log (nameJ)
    eval(l+k+j+ 'Name' + '= ' + nameJ + ';')
    console.log(passenger1Name)

I am getting this output right after the nameJ console.log

VM321:1 Uncaught SyntaxError: Unexpected identifier at pageLoad

Anyone know how can I solve this or approach this differently? Unfortunately, I can't change the variables names (e.g. passengerXName) to one that would make it easier to assign dynamic variables.

Thank you

question from:https://stackoverflow.com/questions/65945143/using-eval-uncaught-syntaxerror-unexpected-identifier-at-pageload

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I have since 1996 or so RARELY seen any reason for eval

This is recommended

const rides = [
{ passengerDetails: {first:"Fred",last:"Flinstone"}},
{ passengerDetails: {first:"Wilma",last:"Flinstone"}}
]

const names = rides.map(ride => `${ride.passengerDetails.first} ${ride.passengerDetails.last}`)
console.log(names)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...