Javascript.RU

Операторы, их особенности в JS

Update: Более новый материал по этой теме находится по адресу https://learn.javascript.ru/operators.

В Javascript есть все необходимые для жизни операторы, хотя нет их перегрузки.

Некоторые операторы(+,побитовые,логические,===) имеют специфические особенности.

В Javascript есть даже операторы >>> и <<<.

  • +
  • -
  • *
  • /
  • %

В отличие от некоторых других языков, оператор "+" делает конкатенацию, если хотя бы один операнд - строка, причем, не обязательно первый.

Проверим:

Унарный оператор "+" также используется для преобразования строки к числу:

alert(+"123"+1) // 124
  • &
  • |
  • ^
  • >>
  • >>>
  • <<

Все побитовые операции работают с 4-байтовым signed int.

Операция >>> сдвигает побитово вправо, а слева нулями дополняет. В результате эффект - тот же, что и при простом сдвиге >> для положительных чисел.

Для отрицательных - все по-другому. Например, -9 в битовом виде выглядит как: 11111111111111111111111111110111.

Операция >>> даст эффект: -9 >>> 2 будет в битовом виде 00111111111111111111111111111101, т.е 1073741821.

  • &&

Логическое И. Возвращает последний операнд, если все операнды верны. Если хоть один из операндов неверен, то возвратит первый неверный операнд.

Например, 1 && 2 = 2:

1 && 0 && false === 0:

Оператор И обычно используется, чтобы избежать ошибок при получении вложенных свойств объекта.

Например, нужно свойство petShop.animals.rabbit или ложное значение, если такого свойства нет.

Безопасный способ:

var rabbit = petShop && petShop.animals && petShop.animals.rabbit

Этот код корректно выполнится, даже если petShop = false, в то время как

var rabbit = petShop.animals.rabbit

выдаст ошибку(бросит исключение) об отсутствующем свойстве.

  • ||

Оператор логического ИЛИ возвращает первое верное значение. А если верных значений вообще нет, то последнее неверное.
Это удобно использовать так:

var e = event || window.event // если event не событие, то берем window.event
  • !

Логическое НЕ, также удобно для преобразования в Boolean.

var str = "something"
// эквивалентные записи
var test = Boolean(str)
var test = !!str
  • ==
  • !=
  • <
  • >
  • <=
  • >=
  • ===
  • !==

Операторы больше-меньше также работают со строками, сравнивая их лексикографически, т.е посимвольно.

"B">"a"
"bc" < "bd"

Сравнение == делается с приведением типов, а === без приведения типов, например:

0 == false  // верно
// но 
0 !== false  //типы разные
Проверка равенства осуществляется особым образом, если один из операндов - undefined, null, NaN. Более подробно об алгоритме в этом случае можно прочитать в секции 11.9.3 стандарта ECMA-262.
  • ?

Тернарный оператор. В старых парсерах javascript с ним были проблемы, надо было заключать сравнение в скобки, но в новых - вполне нормальный оператор

var test = (1==2) ? "one" : "two"
// эквивалентно
var test = 1==2 ? "one" : "two"

Автор: keo nha cai (не зарегистрирован), дата: 8 сентября, 2022 - 05:06
#permalink

I am very impressed with your writing keonhacai I couldn't think of this, but it's amazing! I wrote several posts similar to this one, but please come and see!


Автор: dedrakong, дата: 11 сентября, 2022 - 07:26
#permalink

I can’t tell you when or where exactly, but I have read similar articles in the past, and I’m 100% sure about it.


Автор: Megs (не зарегистрирован), дата: 14 сентября, 2022 - 11:47
#permalink

Please keep up the good work, and I eagerly await more of your fantastic blog postings.
gėlės į namus Kaune


Автор: Гость (не зарегистрирован), дата: 1 октября, 2022 - 20:27
#permalink

Автор: dedrakong, дата: 8 октября, 2022 - 08:41
#permalink

Anyone managed to handle tunnel rush laziness before? I’m too lazy : (


Автор: 카지노게임사이트 (не зарегистрирован), дата: 8 октября, 2022 - 09:26
#permalink

When I read an article on this topic, 카지노게임사이트 the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?


Автор: 무료야동 (не зарегистрирован), дата: 13 октября, 2022 - 09:46
#permalink

Great post 조개모아! I am actually getting 무료성인야동ready to across this information 무료야동사이트, is very helpful my friend 한국야동. Also great blog here 실시간야동 with all of the valuable information you have 일본야동. Keep up the good work 성인사진 you are doing here 중국야동. 무료야동


Автор: 먹튀검증 (не зарегистрирован), дата: 13 октября, 2022 - 09:48
#permalink

Great post 먹튀중개소! I am actually getting 토토사이트ready to across this information 먹튀검증, is very helpful my friend 온라인카지노. Also great blog here 먹튀검증사이트 with all of the valuable information you have 안전놀이터. Keep up the good work 먹튀사이트 you are doing here 먹튀사이트. 검증사이트


Автор: 먹튀사이트 (не зарегистрирован), дата: 13 октября, 2022 - 09:48
#permalink

Автор: 신규사이트 (не зарегистрирован), дата: 13 октября, 2022 - 09:49
#permalink

Автор: 스포츠분석 (не зарегистрирован), дата: 13 октября, 2022 - 09:49
#permalink

Автор: Giser (не зарегистрирован), дата: 13 октября, 2022 - 23:34
#permalink

Google it, I hate when people tell me to Google it, like don’t you have your own opinion? https://unblockeddrifthunters.com


Автор: 샌즈카지노 도메인 (не зарегистрирован), дата: 14 октября, 2022 - 08:24
#permalink

샌즈카지노 도메인 Winning Strategy " 3 in 1 System " By Gambling Chi 8/13/20


Автор: keonhacai (не зарегистрирован), дата: 18 октября, 2022 - 10:36
#permalink

Really no matter if someone doesn't be aware of after that its up to other users that they will help, so here it takes place keonhacai.


Автор: shemalesex (не зарегистрирован), дата: 18 октября, 2022 - 20:07
#permalink

For your own sexy chat experience with hot ladies in UK visit our web platform shemalesex


Автор: 먹튀검증 (не зарегистрирован), дата: 24 октября, 2022 - 09:09
#permalink

Hi there! I could have sworn Iíve visited this site before but after looking at some of the posts I realized itís new to me. Nonetheless, Iím certainly pleased I came across it and Iíll be bookmarking it and checking back regularly! 먹튀검증


Автор: 먹튀검증 (не зарегистрирован), дата: 24 октября, 2022 - 09:10
#permalink

Hi there! I could have sworn Iíve visited this site before but after looking at some of the posts I realized itís new to me. Nonetheless, Iím certainly pleased I came across it and Iíll be bookmarking it and checking back regularly!먹튀검증


Автор: 토토사이트추천 (не зарегистрирован), дата: 24 октября, 2022 - 09:54
#permalink

I am incapable of reading articles online very often, but I’m happy I did today. It is very well written, and your points are well-expressed. I request you warmly, please, don’t ever stop writing.Do you want to buy the best Chromebook for artists? Below we have picked out the top 9 to help you with your decision. Click the blue buttons for more info on Amazon.com
토토사이트추천


Автор: 먹튀사이트 (не зарегистрирован), дата: 24 октября, 2022 - 10:13
#permalink

Very good blog post.Much thanks again. Cool..Hello I am so delighted I located your blog, I really located you by mistake, while I was watching on google for something else, Anyways I am here now and could just like to say thank for a tremendous post and a all round entertaining website. Please do keep up the great work.Without fail, your writing style is top professional; even your website also looks amazing thank you for posting.
먹튀사이트


Автор: 무료성인야동 (не зарегистрирован), дата: 24 октября, 2022 - 12:06
#permalink

Great post 조개모아! I am actually getting 무료성인야동ready to across this information 무료야동사이트, is very helpful my friend 한국야동. Also great blog here 실시간야동 with all of the valuable information you have 일본야동. Keep up the good work 성인사진 you are doing here 중국야동. 무료야동


Автор: 검증사이트 (не зарегистрирован), дата: 24 октября, 2022 - 12:14
#permalink

A great place for kids' edutainment. Being a custom packaging boxes company, we proudly manufacture perfect custom toy boxes for your kids because we believe kids to be our bright future. so we should exert our energies for producing better products for them..Its a great pleasure reading your post.Its full of information I am looking for and I love to post a comment that "The content of your post is awesome" Great work.
검증사이트


Автор: 가입머니 (не зарегистрирован), дата: 24 октября, 2022 - 12:38
#permalink

I was reading some of your content on this website and I conceive this internet site is really informative ! Keep on putting up. ..I read this article. I think You put a lot of effort to create this article. I appreciate your work..This is a brilliant blog! I'm very happy with the comments!.. 가입머니


Автор: 먹튀검증 (не зарегистрирован), дата: 24 октября, 2022 - 12:52
#permalink

This is actually the kind of information I have been trying to find. Thank you for writing this information..Recognizes for paper such an advantageous creation, I lurched adjacent to your blog other than decode a restricted report. I need your system of engraving..Thanks for a very interesting blog. What else may I get that kind of info written in such a perfect approach? I’ve a undertaking that I am simply now operating on, and I have been at the look out for such info.
먹튀검증


Автор: 먹튀검증 (не зарегистрирован), дата: 24 октября, 2022 - 12:53
#permalink

I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.먹튀검증


Автор: 토토사이트 (не зарегистрирован), дата: 24 октября, 2022 - 13:14
#permalink

ove to read it,Waiting For More new Update and I Already Read your Recent Post its Great Thank..great article. thank you for sharin..Great post. Thank You For Sharing Valuable. information. It is Very Informative article..I urge you to peruse this content it is fun portrayed ..
토토사이트


Автор: 먹튀검증 (не зарегистрирован), дата: 24 октября, 2022 - 13:40
#permalink

Really impressed! Everything is very open and very clear clarification of issues. It contains truly facts. Your website is very valuable. Thanks for sharing..Good to become visiting your weblog again, it has been months for me. Nicely this article that i've been waited for so long. I will need this post to total my assignment in the college, and it has exact same topic together with your write-up. Thanks, good share
먹튀검증


Автор: 메이저놀이터 (не зарегистрирован), дата: 24 октября, 2022 - 14:21
#permalink

A great content material as well as great layout. Your website deserves all of the positive feedback it’s been getting. I will be back soon for further quality contents..Hello, I have been using the service for many websites, but when I found your website, it was amazing. Thank you for sharing such good information. 메이저놀이터


Автор: 먹튀검증 (не зарегистрирован), дата: 24 октября, 2022 - 14:34
#permalink

There are incredibly plenty of details like that take into consideration. That is the fantastic specify raise up. I offer the thoughts above as general inspiration but clearly you can find questions such as the one you raise up where the most critical factor will probably be doing work in honest very good faith. I don?t know if guidelines have emerged about things like that, but More than likely that your particular job is clearly identified as a fair game. Both boys and girls notice the impact of a moment’s pleasure
먹튀검증


Автор: 사설토토 (не зарегистрирован), дата: 24 октября, 2022 - 14:40
#permalink

I gotta favorite this website it seems very helpful ..You have a good point here!I totally agree with what you have said!!Thanks for sharing your views...hope more people will read this article!!..I admire this article for the well-researched content and excellent wording. I got so involved in this material that I couldn’t stop reading. I am impressed with your work and skill. Thank you so much. 사설토토


Автор: ygfv (не зарегистрирован), дата: 24 октября, 2022 - 14:59
#permalink

Appreciate it for this post, I am a big fan of this web site would like to go on updated...Your mode of telling everything in this paragraph is really pleasant, all can easily know it, Thanks a lot...These are in fact enormous ideas in on the topic of blogging.You have touched some fastidious factors here. Any way keep up wrinting.
토토사이트


Автор: 토토사이트 (не зарегистрирован), дата: 24 октября, 2022 - 17:15
#permalink

Really impressed! Everything is very open and very clear clarification of issues. It contains truly facts. Your website is very valuable. Thanks for sharing..Good to become visiting your weblog again, it has been months for me. Nicely this article that i've been waited for so long. I will need this post to total my assignment in the college, and it has exact same topic together with your write-up. Thanks, good share 토토사이트


Автор: 먹튀검증 (не зарегистрирован), дата: 24 октября, 2022 - 17:58
#permalink

I am sure this article has touched all the internet people, its really really nice paragraph on building up new blog...These are really fantastic ideas in on the topic of blogging. You have touched some fastidious things here. Any way keep up wrinting.
먹튀검증


Автор: 카지노사이트 (не зарегистрирован), дата: 10 ноября, 2022 - 11:37
#permalink

This is the post I was looking for. I am very happy to read this article. If you have time, please come to my site 카지노사이트 and share your thoughts. Have a nice day.
cfhgh


Автор: 파워맨사이트 (не зарегистрирован), дата: 10 ноября, 2022 - 13:22
#permalink

It&rsquo;s too bad to check your article late. I wonder what it would be if we met a little faster. I want to exchange a little more, but please visit my site&nbsp;bitcoincasino&nbsp;and leave a message!!파워맨사이트


Автор: Ipomi (не зарегистрирован), дата: 11 ноября, 2022 - 20:52
#permalink

Life is not easy at all, at least for most of us, in order to survive, we have to work constantly, over and over again. https://idlebreakout.us


Автор: 수원 카지노 (не зарегистрирован), дата: 12 ноября, 2022 - 07:01
#permalink

Thanks for the valuable information and insights you have provided here. 수원 카지노


Автор: 카지노게임사이트 (не зарегистрирован), дата: 12 ноября, 2022 - 07:45
#permalink

When I read an article on this topic, 카지노게임사이트 the first thought was profound and difficult, and I wondered if others could understand.. My site has a discussion board for articles and photos similar to this topic. Could you please visit me when you have time to discuss this topic?


Автор: Paaser (не зарегистрирован), дата: 14 ноября, 2022 - 13:38
#permalink

I can’t stop eating when I am stressed, stress can actually help to gain weight rather than lose it. doge miner 2 game


Автор: 토토사이트 (не зарегистрирован), дата: 14 ноября, 2022 - 22:11
#permalink

We believe in adding value to our customers by allowing them to focus on their core business while outsourcing the complete uniform supply function to us. When the bell of happiness rings, a couple of new people face a bright future, and offer my most sincere blessings, I wish you both a happy wedding! To tie the knot! Beautiful moments last forever, love until the days are old! I simply would like to give a huge thumbs up for the good data you have here on this post. I will probably be coming again to your weblog for more soon. We need each client to have the option to recruit an assignment writer effectively, with no problem or inconveniences.


Автор: dedrakong, дата: 17 ноября, 2022 - 20:03
#permalink

I really enjoy typing fast and listening to the music at the same time, I kind of feel motivated.


Автор: 토토사이트 (не зарегистрирован), дата: 21 ноября, 2022 - 15:45
#permalink

Nice to meet you. I am so glad to see your article even now. I will always support your writing. 토토사이트


Автор: 메이저안전놀이터 (не зарегистрирован), дата: 21 ноября, 2022 - 15:45
#permalink

Your writing has helped me grow. If I can meet your writings in the future, I think I will grow even more. thank you 메이저안전놀이터


Автор: 시알리스 (не зарегистрирован), дата: 21 ноября, 2022 - 16:29
#permalink

I saw your article well. You seem to enjoy for some reason. We can help you enjoy more fun. Welcome anytime시알리스


Автор: 카지노게임사이트 (не зарегистрирован), дата: 22 ноября, 2022 - 09:52
#permalink

Hello! I could have sworn I've been to this site before but after checking through some of the post I realized it's new to me. Nonetheless, I'm definitely happy I found 카지노게임사이트 and I'll be book-marking and checking back frequently!


Автор: 바카라사이트추천 (не зарегистрирован), дата: 22 ноября, 2022 - 10:32
#permalink

Hello ! I am the one who writes posts on these topics 바카라사이트추천 I would like to write an article based on your article. When can I ask for a review?


Автор: 온라인카지노 (не зарегистрирован), дата: 23 ноября, 2022 - 07:15
#permalink

What a post I've been looking for! I'm very happy to finally read this post. 온라인카지노 Thank you very much. Can I refer to your post on my website? Your post touched me a lot and helped me a lot. If you have any questions, please visit my site and read what kind of posts I am posting. I am sure it will be interesting.


Автор: 온라인바카라 (не зарегистрирован), дата: 23 ноября, 2022 - 09:48
#permalink

I’m not sure exactly why but this weblog is loading incredibly slow for me. Is anyone else having this problem or is it a problem on my end? I’ll check back later on and see if the problem still exists. 온라인바카라
xdgff


Автор: makeup artist atlanta (не зарегистрирован), дата: 24 ноября, 2022 - 14:30
#permalink

Your Blog is very nice. Wish to see much more like this. Thanks for sharing your information.


Автор: zkwlshzjabslxl (не зарегистрирован), дата: 1 декабря, 2022 - 09:56
#permalink

I can't believe that I feel like I'm in a new world that I don't know with just one sentence. 카지노커뮤니티 I think good writing has a lot of power


Автор: 를롯사이트 (не зарегистрирован), дата: 1 декабря, 2022 - 15:45
#permalink

cooool~~!! It was a very good post. I wish there were more posts like this, I will visit you often. I cheer for you. 슬롯사이트


Автор: allanpetter, дата: 2 декабря, 2022 - 03:55
#permalink

This is really great!


Автор: allanpetter, дата: 2 декабря, 2022 - 03:56
#permalink

This is really great!


Отправить комментарий

Приветствуются комментарии:
  • Полезные.
  • Дополняющие прочитанное.
  • Вопросы по прочитанному. Именно по прочитанному, чтобы ответ на него помог другим разобраться в предмете статьи. Другие вопросы могут быть удалены.
    Для остальных вопросов и обсуждений есть форум.
P.S. Лучшее "спасибо" - не комментарий, как все здорово, а рекомендация или ссылка на статью.
Содержание этого поля является приватным и не предназначено к показу.
  • Адреса страниц и электронной почты автоматически преобразуются в ссылки.
  • Разрешены HTML-таги: <strike> <a> <em> <strong> <cite> <code> <ul> <ol> <li> <dl> <dt> <dd> <u> <i> <b> <pre> <img> <abbr> <blockquote> <h1> <h2> <h3> <h4> <h5> <p> <div> <span> <sub> <sup>
  • Строки и параграфы переносятся автоматически.
  • Текстовые смайлы будут заменены на графические.

Подробнее о форматировании

CAPTCHA
Антиспам
1 + 1 =
Введите результат. Например, для 1+3, введите 4.
 
Текущий раздел
Поиск по сайту
Содержание

Учебник javascript

Основные элементы языка

Сундучок с инструментами

Интерфейсы

Все об AJAX

Оптимизация

Разное

Дерево всех статей

Последние комментарии
Последние темы на форуме
Forum