nemoluca ([info]nemoluca) wrote in [info]ru_webdev,
@ 2007-07-05 15:55:00
Previous Entry  Add to memories!  Tell a Friend!  Next Entry
непонятно поведение eval()
вот так работает
var str = '[' + '{id:123, content:"test"}' + ']';
var obj = eval(str)[0];
alert(obj.id);
а так - нет:
var str = '{id:123, content:"test"}';
var obj = eval(str);
alert(obj.id);
почему?



(Post a new comment)

имхо
[info]a1ive
2007-07-05 12:24 pm UTC (link)
Странно, что первый вариант работает...
В первом и во втором случае создаются просто безымянные массив и хеш.

Правильнее будет так, наверное:

var str = 'obj = {id:123, content:"test"}';
var obj;
eval(str);
alert(obj.id);

(Reply to this) (Thread)

Re: имхо
[info]nemoluca
2007-07-05 04:35 pm UTC (link)
думаю "безымянность" весьма условна, т.к. нельзя создать что-то и чтобы оно где-то не лежало :)
поэтому склоняюсь больше ко второму варианту (со скобками), впрочем Ваше решение тоже подходит. Спасибо!

(Reply to this) (Parent)


[info]4vanger
2007-07-05 12:46 pm UTC (link)
честно говоря никак не могу вспомнить с чем это связано, но солюшен такой:
var str = '({id:123, content:"test"})';
var obj = eval(str);
alert(obj.id);

(Reply to this) (Thread)


[info]shabunc
2007-07-05 12:49 pm UTC (link)
да, с чем связано тоже не сформулирую чётко,
но иначе просто вернёт 123.

(Reply to this) (Parent)

вот почему
[info]shabunc
2007-07-05 12:54 pm UTC (link)
Нашёл!
http://www.thescripts.com/forum/thread499662.html
When encountered on the left hand side, the punctuator '{' defines the
start of a block statement, like if{... or while{... etc. The stuff
inside the block is evaluated as if it were a series of statements, so
the script engine attempts to evaluate:

(Reply to this) (Parent)


[info]nemoluca
2007-07-05 04:42 pm UTC (link)
спасибо, все работает!

(Reply to this) (Parent)


[info]hatifnaftt
2007-07-05 09:19 pm UTC (link)
eval is evil

(Reply to this) (Thread)


[info]shabunc
2007-07-06 12:00 pm UTC (link)
вы о JSON имеете представление?

(Reply to this) (Parent)(Thread)


[info]vlad_drakula
2007-07-06 05:04 pm UTC (link)
JSON далеко не единственный способ передачи данных.

(Reply to this) (Parent)


[info]hatifnaftt
2007-07-06 09:46 pm UTC (link)
Да, достаточное ;)
Оригинал (полный текст):
"eval is evil
JSON is a handy, comprehensive format to store/transmit data, especially when working with JavaScript. The syntax looks something like this:
var obj = {key1: value1, key2: [value2, value3]}
And the good thing in JavaScript is, that all you need to do in order to convert a string into an according object or array, is to call "eval(.)" on that string.
Well, well, this "good" thing is actually a very "bad" thing (especially on the server side, i.e. in helma), since it might encourage programmers to call eval on all kind of unsafe strings. Fortunately there is a free javascript-library available at http://www.crockford.com/JSON/js.html, which parse such strings in a safe way. This library can and should always be used instead of eval!"

Удачи.

(Reply to this) (Parent)


Create an Account
Forgot your login or password?
Login w/ OpenID
English • Español • Deutsch • Русский…