developer tip

자바 스크립트 속성 이름에 대시가 허용 되나요?

copycodes 2021. 1. 10. 17:29
반응형

자바 스크립트 속성 이름에 대시가 허용 되나요?


jQuery 용 간단한 플러그인을 만들기 위해 http://docs.jquery.com/Plugins/Authoring#Defaults_and_Options보고있었습니다 . 옵션 및 설정에 대한 섹션에 따라 다음 작업을 수행했지만 작동하지 않았습니다 (스크립트가 설정을 만나면 종료 됨).

var settings = {
    'location' : 'top',
    'background-color': 'blue'
}
...
$this.css('backgroundColor', settings.background-color); // fails here

배경색에서 대시를 제거하면 제대로 작동합니다.

var settings = {
    'location' : 'top',
    'backgroundColor': 'blue' // dash removed here
}
...
$this.css('backgroundColor', settings.backgroundColor); 

내가 뭔가를 놓치고 있거나 jQuery 문서가 잘못 되었습니까?


아니. 파서는이를 빼기 연산자로 해석합니다.

당신은 할 수 있습니다 settings['background-color'].


변경 settings.background-colorsettings['background-color'].

-빼기 연산자로 읽히므로 변수에 포함될 수 없습니다 .


대시는 자바 스크립트 변수에서 유효하지 않습니다. 변수 이름은 문자, 달러 기호 또는 밑줄로 시작해야하며 뒤에 같거나 숫자가 올 수 있습니다.


문자열에 대시를 사용할 수 있습니다. 정말로 그 대시를 유지하고 싶다면 대괄호 등을 사용하여 속성을 참조해야합니다.

$this.css('backgroundColor', settings['background-color']);

다음과 같이 할 수 있습니다.

var myObject = {
  propertyOne: 'Something',
  'property-two': 'Something two'  
}

var result1 = myObject.propertyOne
var result2 = myObject['propertyOne']
var result3 = myObject['property-two']

참조 URL : https://stackoverflow.com/questions/5516106/are-dashes-allowed-in-javascript-property-names

반응형