2012-04-13 4 views
59

하는 이유는 무엇입니까 ...무엇이 오류`string.split is not function`의 원인입니까? 내가 실행

Uncaught TypeError: string.split is not a function

...

(function() { 
 
    var string = document.location; 
 
    var split = string.split('/'); 
 
})();

+2

을 원하는이

// you'll see that it prints Object console.log(typeof document.location); 

는'document.location'는 객체입니다. 시도해보십시오 :'var string = document.location.href' – Teemu

답변

125

변경이 ...

var string = document.location; 

이것에 ...

var string = document.location + ''; 

document.locationLocation object입니다. 기본값 .toString()은 문자열 형식으로 위치를 반환하므로 연결하면 해당 위치가 트리거됩니다.


문자열을 얻으려면 document.URL을 사용할 수도 있습니다. 현재 URL

+22

해키 연결 대신'toString()'을 호출하는 것이 더 깔끔하지 않을까요? – kapa

+1

@ bažmegakapa : 그래, 그건 특혜의 문제 야. '+ ''는 문자열 강제에 대한 꽤 흔한 트릭이지만, 어떤 사람들은'toString()'메소드를 선호한다. 숫자 변환을 위해 단항'+'을 사용하는 것보다 더 이상 해커라고 생각하지 않을 것입니다. –

+2

그건 그냥 못생긴 것입니다. 'parseInt()'와'parseFloat()'가 있습니다. 'Number()'도 있습니다. '+'는 더 짧지 만 해킹 코드 나 경험이 적은 사람에게는 읽기 쉽지 않습니다. – kapa

39

문자열이 아닙니다.

아마도 document.location.href 또는 document.location.pathname을 대신 사용하고 싶을 것입니다.

2

document.location을 원하는 가정 어쩌면

string = document.location.href; 
arrayOfStrings = string.toString().split('/'); 

+0

권. 동시에 4 답변 (적어도). 나는 SO에 대한 최신 질문을 보지 말아야한다. –

6

는 실행이 document.location.toString() 또는 document.location.href

+0

고맙습니다. 내 var를 문자열에서 객체로 변환한다는 것을 깨닫지 못했습니다. 당신의 솔루션은 내 코드를 다시 체크 할 수있는 아이디어를주었습니다. – sg552

관련 문제