2014-11-24 2 views
1

아래의 JavaScript 코드를 한 줄짜리 코드로 작성하는 방법이 있습니까?One-Liner with Return Stat

this.isContactPage = (window.location.pathname === '/contact'); 
if (!this.isContactPage) return false; 

this.isContactPage이 참이면이 방법이 계속된다.

스크립트의 다른 위치에는 this.isContactPage 속성이 필요합니다.

+0

무엇을 돌려 주어야합니까? – xandercoded

+0

죄송합니다! '!'. 이 메서드는 조건이 true 인 경우 계속 진행됩니다. – cantera

답변

2

그것은 매우 조밀하고 "가려"코드 수 있습니다,하지만 당신은 조건문에 할당 인라인 할 수 있습니다

if (!this.isContactPage = (window.location.pathname == '/contact')) return false; 

이를 this.isContactPage에값이 할당 된 경우에만 함수를 반환합니다. 즉시 true 또는 false를 반환합니다

return (this.isContactPage = (window.location.pathname == '/contact')); 

: 반대로그렇지 않으면 함수는 반환 및 실행에 계속되지 않습니다.

+0

나는 그것을 좋아한다. 당신이 말한대로 조금 조밀 한,하지만 여전히 두 줄을 나누는 것보다 낫다. – cantera

+0

실제로이 방법이 효과가 있습니까? JS Bin과 JSFiddle은 혼란스러워 보입니다. http://jsbin.com/qonecoboje/1/edit – cantera

+0

jsbin에서 jQuery를 포함하고 페이지 준비 함수에 코드를 래핑하는 것을 잊었습니다. 이 편집보기 : http://jsbin.com/puwuvajuda/1/edit?html, js, 출력 –

5
return !(this.isContactPage = (window.location.pathname === '/contact')); 

또 다른 예 :

console.log(window.prop); // undefined 
console.log(!(window.prop = true) || undefined); // undefined 
console.log(!(window.prop = true)); // false 
console.log(window.prop); // true 
+1

같은 대답, 같은 시간. 위대한 마음은 비슷하게 생각합니다 :) –

+0

@AlexMcp - 좋은 사람 :) .. –

+1

이것은 OP와는 행동이 다르지 않습니까? 'this.isContactPage'에'true'가 지정되면 OP만이 리턴됩니다. 이것은 어느 쪽이든 반환합니다. –

1

return !this.isContactPage = (window.location.pathname === '/contact')

1

함께 오류가 발생하지 않습니다! 내가 뭔가를

this.isContactPage = /contact/gi.test(window.location.pathname); 
if (!this.isContactPage) return false; 

또는

return !(/contact/gi.test(window.location.pathname)) 
+1

재미 있고, 정규식을 사용하지 않을 생각이었습니다 – cantera

+1

더 정확한 정규 표현식은'/^\/contact $/i'입니다. 그렇지 않으면 모든 "contact"라는 단어가 포함 된 경로 이름. –

1

은 당신의 코드를 가능한 한 짧게한다!

return !(this.isContactPage=location.pathname=='/contact') 
  1. 당신은 당신이 다음 =로 변경, === 필요가 없습니다 코드
  2. 를 통해 허위 또는 직접 진실을 반환하지 않아도 "창"
  3. 필요하지 않습니다 = 사람들이 제안한 가장 짧은 방법은 88 자이며이 제안은 68 자이며 읽기 쉽고 이해할 수 있습니다! `this.isContactPage`가`false` 인 경우
+0

응답을위한 Thx - 'window'는 선택 사항이 아닙니다. 확인 : https://developer.mozilla.org/en-US/docs/Web/API/Location – cantera