Javascript

update create

Pure JavaScript関連のメモ。
トランスパイル (トランスコンパイラ) 関連は別途。

基本

document.getElementById('ID名');
document.getElementsByTagName('タグ名');
document.getElementsByClassName('クラス名');
document.getElementsByName('name属性');
document.querySelectorAll('[データ属性]');

mozilla参考

element.setAttribute(name,value);
var attribute = element.getAttribute(attributeName);
var result = element.hasAttribute(attName);
element.removeAttribute(attrName);

意図しない動作

pseudoは、微妙。

window.getComputedStyle(element, ':valid').getPropertyValue('border-color');

contentEditable

javascript:(function(b){b.contentEditable=!b.isContentEditable;})(document.body);

Scroll Junk

https://developers.google.com/web/updates/2016/06/passive-event-listeners?hl=ja https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md

Base64

日本語を使わない

window.btoa(text);
window.atob(b64data);

日本語使用

window.btoa(unescape(encodeURIComponent(text))); 
ecodeURIComponent(escape(window.atob(b64data))); 

変数の巻き上げ(hoisting)

下記コードは、

var myname = "global";
function func() {
    console.log(myname); 
    var myname = "local";
    console.log(myname); 
}
func();

下記と解釈されるため、最初のログがundefineになるJavascript特有の現象。

function func() {
    var myname;
    console.log(myname);
    myname = "local";
    console.log(myname);
}
func();

JavaScriptでは、関数内で宣言されたローカル変数は、すべてその関数の先頭で宣言されたものとみなされる。

日時

nativeawareが微妙。
moment を使ったほうが良い気がする。

var dt = Date.parse('2011-01-01')
var ojbDt = new Date(dt)

dtはunix秒になってる。
以前は日付だった気がするのだけれど、、
parseがブラウザやバージョンによって微妙。
UTCとして解析される。
Z,GMT, UTCなどのawareな情報が記載された場合は、それに従って解析される。
(※解析できない環境もあるっぽい)
保持は基本UTCと思って間違いないと思う。
なので、明示的に意識しないとデプロイされる環境によって挙動が異なるので注意。
書式が使えないので自前でpadding

('00' + dt.getDate()).slice(-2)

moment

var now = moment()
console.log(now.toDate())
var native_now = new Date()
var moment_now = moment(native_now)
console.log(moment_now.format("YYYY-MM-DD"))

JSON

Google JSON Style Guide

JsonSchema

macos

brew install nodebrew

notebrew ls-remote

mkdir -p ~/.nodebrew/src

nodebrew install-binary stable

koich@mikaka jsonschema % nodebrew ls
v14.15.0

current: none
koich@mikaka jsonschema % nodebrew use v14.15.0
use v14.15.0


pathの追加
echo 'export PATH=$HOME/.nodebrew/current/bin:$PATH' >> ~/.zprofile

npm install -g quicktype

https://quicktype.io/

http://json-schema.org/understanding-json-schema/ http://json-schema.org/understanding-json-schema/reference/string.html#length

JSON for Linking Data

Data is messy and disconnected. JSON-LD organizes and connects it, creating a better Web. https://schema.org/docs/gs.html