表示ä¸ã®HTMLããæ å ±ãéã«æãåºãã¦å©ç¨ããããï¼ãã©ã¦ã¶ã®ããããããã¼ã«ãªã©ã§querySelectorAllãã¦mapãããï¼ãããï¼querySelectorAllã¯NodeListãè¿ãã®ã§ï¼mapããã«ã¯Arrayã«å¤æããå¿ è¦ãããï¼
NodeListãArrayã«å¤æããã¨ãã«çãæ¸ãæ¹æ³ãªãã§ããã£ã¦ååã«èãããããããæãã¦ããããã®ã§ã¡ã¢ï¼
Array.prototype.slice.callãã
ãªã¼ã½ããã¯ã¹ãªææ³ï¼æãããããæ¸ãã¦ãã¦ï¼é·ãã¦å°ã£ã¦ããï¼æè¿ã¯ã¢ãã¼é¢æ°ã使ããã®ã§ã¡ãã£ã¨çããªã£ããã©é·ãï¼
Array.prototype.slice.call(document.querySelectorAll('a')).map(a => a.href)
[].slice.callãã
Array.prototypeã®ãããã«[]
ã§æ¸ãï¼ã¡ãã£ã¨çãï¼
[].slice.call(document.querySelectorAll('a')).map(a => a.href)
Array.fromãã
æè¿ã¯ããã§æ¸ããã¨æãã¦ããã£ãï¼[].slice
ã¨æåæ°å¤ãããªããã©ï¼ãã¡ãã®ã»ãã宣è¨çãªæ°ãããï¼
Array.from(document.querySelectorAll('a')).map(a => a.href)
Array.from() ã¡ã½ããã¯ãé åå (array-like) ãªãã¸ã§ã¯ããå復å¯è½ (iterable) ãªãã¸ã§ã¯ãããæ°ãã Array ã¤ã³ã¹ã¿ã³ã¹ãçæãã¾ãã
Array.from() - JavaScript | MDN
[…ãã
ã¹ãã¬ããæ¼ç®åã使ã£ãå·§ã¿ãªæï¼ãããã¯ã·ã§ã³ã®ã³ã¼ãã§ä½¿ããã¨ã¯ãªãããã ãã©ï¼ããããããã¼ã«ã§ã¡ãã£ã¨æ¸ãããããªããããä¸çªçãã¦ããããï¼
[...document.querySelectorAll('a')].map(a => a.href)
調ã¹ããåããããªè©±é¡ãstackoverflowã§å±éããã¦ããï¼2010å¹´ã®è³ªåã ãã©ï¼2015å¹´ã«ãªã£ã¦ï¼ES6ãªãããæ¸ããã£ã¦åçãã¤ãã¦ãã¦ãããããï¼
追è¨ï¼ $$
ããããããã¼ã«ã§ã¯document.querySelectorAllã¯$$ã§å¼ã¹ã¦ï¼ãã¤è¿ãå¤ãArrayã«å¤æãã¦ããã¦ããã®ã§ï¼ç´æ¥mapå¼ã¹ããããï¼ä¸è¨ããããªå·¥å¤«ã¯å ¨ããã£ã¦ä¸è¦ã ã£ãâ¦
$$('a').map(a => a.href)
Arrayã«å¤æãã¦ããããã¨ã¯ããã¥ã¡ã³ãã«è¼ã£ã¦ãªããã©ï¼ãããã«è¿ãå¤ã¯Arrayã«ãªã£ã¦ããï¼
$$(selector) ã¯ãæå®ããã CSS ã»ã¬ã¯ã¿ã¼ã«ä¸è´ããè¦ç´ ã®é åãè¿ãã¾ãããã®ã³ãã³ãã¯ãdocument.querySelectorAll() ã®å¼ã³åºãã¨åãã§ãã
コマンドライン API リファレンス | Web | Google Developers
querySelectorAllãã¦mapãããã¨ã[...ããã¨çã - hitode909ã®æ¥è¨devtoolã§æ¸ããªããdocument.querySelectorAllã¯ããã«$$ã«ç½®ãæããããã / æè¿ã®ãã©ã¦ã¶ã ã¨NodeListã«mapã¨ãçãã¦ãã => mapã¯ãªãã¦forEachã ãã ã£ãã($$ã¯NodeListãArrayã«ãã¦ããã¦ã¦åéããã¦ãã¾ã£ã)
2017/04/19 12:19
追è¨(2): æåããmapå¼ã¹ã°ãã
ãã¡ã©Arrayã«å¤æããå¿ è¦ã¯ãªãã¦ï¼[].map.callã«NodeListã¨é¢æ°ã渡ãã°ããï¼ã¨ããã®ãæãã¦ããã£ãï¼ãããã«ï¼
[].map.call(document.querySelectorAll('a'), a => a.href)
querySelectorAllãã¦mapãããã¨ã[...ããã¨çã - hitode909ã®æ¥è¨
- [javascript]
- [ES6]
ã¢ãã¼é¢æ°ã®åå¨ããã£ããå¿ãã¦ãã(ãã£ã¡ï¼ï¼)functionãreturnãçç¥ã§ãã¦æ¥½ã ãã¼ / 1,2çªç®ã®è¨æ³ã ã¨sliceããã®ã¯åé·ã [].map.call(document.querySelectorAll('a'), a => a.href) ã§OKã§ãã
2017/04/19 13:04
追è¨(3): Array.fromã®ç¬¬äºå¼æ°ã«mapFn渡ãã
Array.fromã«é¢æ°ã渡ãã¨mapãã¦ããããããï¼ãµã¤ãã«ããã¥ã¡ã³ãã«æ¸ãã¦ãã£ãã®ã§ã¡ããã¨èªããï¼ã¨ããæ°ã«ãªãã¾ããâ¦â¦
Array.from(document.querySelectorAll('a'), a => a.href)
mapFn
ä»»æãé åã®ãã¹ã¦ã®è¦ç´ ã«å¯¾ãã¦å¼ã³åºããã Map é¢æ°ã
Array.from() - JavaScript | MDN
querySelectorAllãã¦mapãããã¨ã[...ããã¨çã - hitode909ã®æ¥è¨Array.fromã®ç¬¬äºå¼æ°ã«ã³ã¼ã«ããã¯é¢æ°ãæ¸ãã¦ãè¯ãã®ãï¼ï¼å人çã«ã¯ãããªãã«çããåããæãè¨è¿°ã«ãªãã®ã§å¥½ãï¼
2017/04/21 09:40