JavaScript에서 ':'(콜론)은 무엇을합니까?
JavaScript를 배우고 있으며 jQuery 라이브러리를 탐색하는 동안
:
(콜론)이 많이 사용되는 것을 볼 수 있습니다. 이것은 JavaScript에서 무엇을 사용합니까?
// Return an array of filtered elements (r)
// and the modified expression string (t)
return { r: r, t: t };
var o = {
r: 'some value',
t: 'some other value'
};
기능적으로
var o = new Object();
o.r = 'some value';
o.t = 'some other value';
또한 콜론을 사용하여 명령문에 레이블을 지정할 수 있습니다. 예를 들어
var i = 100, j = 100;
outerloop:
while(i>0) {
while(j>0) {
j++
if(j>50) {
break outerloop;
}
}
i++
}
너희들은 콜론이 삼항 연산자에서도 사용된다는 것을 잊어 버린다. (jquery 가이 목적으로 그것을 사용하는지는 모르겠지만).삼항 연산자는 if / then 문의 표현식 양식 (표현식이 값을 리턴 함)입니다. 다음과 같이 사용됩니다.
var result = (condition) ? (value1) : (value2) ;
삼항 연산자를 사용하여 if / then과 같은 부작용을 만들 수도 있지만, 이는 매우 나쁜 습관입니다.
':'은 기본적으로 키 값 쌍의 구분 기호입니다. 귀하의 예에서는 Javascript Object Literal 표기법입니다.자바 스크립트에서 객체는 콜론으로 속성의 식별자와 그 값을 구분하여 정의되므로 다음을 가질 수 있습니다.
return {
Property1 : 125,
Property2 : "something",
Method1 : function() { /* do nothing */ },
array: [5, 3, 6, 7]
};
그런 다음 다음과 같이 사용하십시오.
var o = {
property1 : 125,
property2 : "something",
method1 : function() { /* do nothing */ },
array: [5, 3, 6, 7]
};
alert(o.property1); // Will display "125"
이것의 서브셋은 JSON (Javascript Object Notation)으로도 알려져 있는데, 이는 서버 측 언어로 작고 빠르게 구문 분석하고 Javascript는 JSON 문자열을 객체로 쉽게 직렬화 해제 할 수 있기 때문에 AJAX 호출에 유용합니다.
// The parenthesis '(' & ')' around the object are important here
var o = eval('(' + "{key: \"value\"}" + ')');
특수 문자 또는 공백이 포함되어 있으면 키를 따옴표 안에 넣을 수도 있지만 작업하기가 더 어려워지기 때문에 권장하지 않습니다.
Keep in mind that JavaScript Object Literal Notation in the JavaScript language is different from the JSON standard for message passing. The main difference between the 2 is that functions and constructors are not part of the JSON standard, but are allowed in JS object literals.
It is part of the object literal syntax. The basic format is:
var obj = { field_name: "field value", other_field: 42 };
Then you can access these values with:
obj.field_name; // -> "field value"
obj["field_name"]; // -> "field value"
You can even have functions as values, basically giving you the methods of the object:
obj['func'] = function(a) { return 5 + a;};
obj.func(4); // -> 9
It can be used to list objects in a variable. Also, it is used a little bit in the shorthand of an if sentence:
var something = {face: 'hello',man: 'hey',go: 'sup'};
And calling it like this
alert(something.man);
Also the if sentence:
function something() {
(some) ? doathing() : dostuff(); // if some = true doathing();, else dostuff();
}
Let's not forget the switch statement, where colon is used after each "case".
These are generally the scenarios where colon ':' is used in JavaScript
1- Declaring and Initializing an Object
var Car = {model:"2015", color:"blue"}; //car object with model and color properties
2- Setting a Label (Not recommended since it results in complicated control structure and Spaghetti code)
List:
while(counter < 50)
{
userInput += userInput;
counter++;
if(userInput > 10000)
{
break List;
}
}
3- In Switch Statement
switch (new Date().getDay()) {
case 6:
text = "Today is Saturday";
break;
case 0:
text = "Today is Sunday";
break;
default:
text = "Looking forward to the Weekend";
}
4- In Ternary Operator
document.getElementById("demo").innerHTML = age>18? "True" : "False";
That's JSON, or JavaScript Object Notation. It's a quick way of describing an object, or a hash map. The thing before the colon is the property name, and the thing after the colon is its value. So in this example, there's a property "r", whose value is whatever's in the variable r. Same for t.
One stupid mistake I did awhile ago that might help some people.
Keep in mind that if you are using ":" in an event like this, the value will not change
var ondrag = (function(event, ui) {
...
nub0x: event.target.offsetLeft + event.target.clientWidth/2;
nub0y = event.target.offsetTop + event.target.clientHeight/2;
...
});
So "nub0x" will initialize with the first event that happens and will never change its value. But "nub0y" will change during the next events.
Another usage of colon in JavaScript is to rename a variable, that is:
const person = {
nickNameThatIUseOnStackOverflow: "schlingel",
age: 30,
firstName: "John"
};
const { nickNameThatIUseOnStackOverflow: nick } = person; // I take nickNameThatIUseOnStackOverflow but want to refer it as "nick" from now on.
nick = "schling";
This is useful if you use a third party library that returns values having awkward / long variable names that you want to rename in your code.
참고URL : https://stackoverflow.com/questions/418799/what-does-colon-do-in-javascript
'programing' 카테고리의 다른 글
올바른 Bash 및 셸 스크립트 변수 대문자 (0) | 2020.05.26 |
---|---|
@charset“UTF-8”을 지정해야하는 이유; (0) | 2020.05.26 |
Markdown 파일에 gif를 추가하는 방법이 있습니까? (0) | 2020.05.25 |
C # : 개체의 모든 속성 인쇄 (0) | 2020.05.25 |
창 관리자 충돌에 첨부되지 않은보기 (0) | 2020.05.25 |