「web備忘録」カテゴリーアーカイブ

普段はwebのほうの仕事も多いのでそちらのお勉強の際のちょっとしたメモ書きです。

[javascript]
<div>

var re = new RegExp('j.*t')

undefined
var re = new RegExp("j.t");
undefined
re
/j.
t/
var re = /j.t/
undefined
re
/j.
t/
re.global
false
re.ignoreCase
false
re.multiline
false
var re = new RegExp("j.t")
undefined
re
/j.
t/
var re = /j.t/ig;
undefined
re
/j.
t/gi
re.ignoreCase
true
re.global
true
re.ignoreCase
true
re.mulreligne
undefined
re.multeline
undefined
re.mulitiline
undefined
re.multiline
false
re.multiline
false
/j.t/.test("javascript");
true
re.test("javascript")
true
/j.
t/i.test('javascript');
true
/j.t/.exec("javascript")[0]
"javascript"
/j.
t/.exec("javascript","eee")[1]
undefined
var s = new String('HellowJavascriptWorld');
undefined
s
String {0: "H", 1: "e", 2: "l", 3: "l", 4: "o", 5: "w", 6: "J", 7: "a", 8: "v", 9: "a", 10: "s", 11: "c", 12: "r", 13: "i", 14: "p", 15: "t", 16: "W", 17: "o", 18: "r", 19: "l", 20: "d", length: 21, [[PrimitiveValue]]: "HellowJavascriptWorld"}
s.match(/a/);
["a"]
s.match(/a/g);
["a", "a"]
s.match(/a/ig);
["a", "a"]
s.match(/j./ig);
["JavascriptWorld"]
s.match(/j.
a/i);
["Java"]
s.match(/j.s/i);
["Javas"]
s.match(/j.
c/i);
["Javasc"]
s.match(/a.c/i);
["avasc"]
s.match(/a.
c/i);
["avasc"]
s.search(/a.c/i);
7
s.search(/j.
c/i);
6
s.search(/j.c/i);
6
s.search(/j.
a/i);
6
s.search(/j.a/i);
6
s.replace(/[A-Z]/g,'');
"ellowavascriptorld"
s.replace(/[a-z]/g,'');
"HJW"
s.replace(/[A-Z]/,'');
"ellowJavascriptWorld"
s.replace(/[A-Z]/,'$&');
"_HellowJavascriptWorld"
s.replace(/[A-Z]/g,'
$&');
"Hellow_Javascript_World"
s.replace(/([A-Z])/g,'
$1');
"Hellow_Javascript_World"
s.replace(/([A-Z])/g,'
$1');
"_Hellow_Javascript_World"
var email = morita@yahoo.co.jp
Uncaught SyntaxError: Unexpected token ILLEGAL VM1156:732
email
Uncaught ReferenceError: email is not defined VM2116:2
var email = 'morita@yahoo.co.jp'
undefined
email
"morita@yahoo.co.jp"
var username = /.
@/i;
undefined
var username = email.replace(/.@/i);
undefined
var username = email.replace(/.
@/i);
undefined
username
"undefinedyahoo.co.jp"
var username = email.replace(/(.)@./,"$1");
undefined
username
"morita"
function replaceCallback(match){return ""+ match.toLowerCase();}
undefined
function replaceCallback(match){return "
"+ match.toLowerCase();}
s.replace(/[A-Z]/g,replaceCallback);
"_hellow_javascript_world"
var glob;
undefined
var re = /(.*)@(.*).(.*)/;
undefined
re
/(.*)@(.*).(.*)/
var callback = function(){
glob = arguments;
return arguments[1] + 'at' + arguments[2] + 'dot' + arguments[3];
}
undefined
"moritakenji@yahoo.co.jp".replace(re,callback);
"moritakenjiatyahoo.codotjp"
var callback = function(){
glob = arguments;
return arguments[1] + ' at ' + arguments[2] + ' dot ' + arguments[3];
}
undefined
"moritakenji@yahoo.co.jp".replace(re,callback);
"moritakenji at yahoo.co dot jp"
glob
["moritakenji@yahoo.co.jp", "moritakenji", "yahoo.co", "jp", 0, "moritakenji@yahoo.co.jp"]ß
</div>
var reg = new RegExp('^[0-9]');
reg.test('foo');
false
reg.test('123');
true
var reg = /'^[0-9]'/;
undefined
var reg = /'^[0-9]'/;
function RegExp(){

}
undefined
var reg = /'^[0-9]'/;
reg.constructor;

function RegExp() { [native code] }
var reg = /'^[0-9]'/g;
var reg = /^\s+/;
undefined
reg
/^\s+/
var reg = new RegExp('^\s+');
undefined
var reg = new RegExp('^\s+');
undefined
reg
RegExp {}
var text = 'abc def ghi jkl';
var reg = /(\w+)\s(\w+)/;
reg.exec(text);
["abc def", "abc", "def"]
var reg = /(\w+)\s(\w+)/g;
undefined
reg
/(\w+)\s(\w+)/g
var text = 'abc def ghi jkl';
undefined
reg.exec(text);
["abc def", "abc", "def"]
reg.exec(text);
["ghi jkl", "ghi", "jkl"]
reg.exec(text);
null
var text = 'moritakenji';
var result = text.search(/^kan/g);
result;
-1
var text = 'moritakenji';
var result = text.search(/^moirta/g);
result;
-1
var text = 'moritakenji';
var result = text.search(/^(moirta)/g);
result;
-1
var text = 'abc def ghi jkl';
text.replace(/\s/,',');
"abc,def ghi jkl"
var text = 'abc def ghi jkl';
text.replace(/\s/g,',');
"abc,def,ghi,jkl"
text.replace(/(.)\s/g,',$1');
"ab,cde,fgh,ijkl"
text.replace(/(.)\s/g,function(01m,02m){return ','+ 02m});
Uncaught SyntaxError: Unexpected token ILLEGAL VM50:732
text.replace(/(.)\s/g,function(m0,m1){return ','+ m1});
"ab,cde,fgh,ijkl"
var text = 'abc def ghi jkl';
undefined
text
"abc def ghi jkl"
text.match(/\w/g);
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]
text.match(/(w+)\s/g);
null
text.match(/(w)\s/g);
null
text.match(/(.)\s/g);
["c ", "f ", "i "]
text.match(/(.)\s/g);
["c ", "f ", "i "]
text.match(/([a-z]{,3})\s/g);
null
text.match(/([a-z]{3})\s/g);
["abc ", "def ", "ghi "]
text.match(/([a-z]{1,2})\s/g);
["bc ", "ef ", "hi "]
text.match(/([a-z]{0,1})\s/g);
["c ", "f ", "i "]
text.match(/([a-z]{3})\s/g);
["abc ", "def ", "ghi "]
text.match(/(\w+)\s(\w+)/g);
["abc def", "ghi jkl"]
[/javascript]

[javascript]
//コンストラクタクラス定義、インスタンス生成、プロトタイプ継承を使った関数を参照
var Menber = function(fname,sname){
this.fname = fname;
this.sname = sname;
};
Menber.prototype.me1 = function(){
return this.fname + this.sname;
}
Menber.prototype.me2 = function(){
return this.fname + this.sname;
}
var men1 = new Menber('morita','kenji');
var men2 = new Menber('kenji','kenji');

// オブジェクトリテラルでのprototype定義

    var Menber = function(fname,sname){
        this.fname = fname;
        this.sname = sname;
    }
    Menber.prototype = {
        add : function(){return this.fname + this.sname},
        add2 : function(){return this.sname + this.fname}
    };
    var men1 = new Menber('ff','ee');
    console.log(men1.add(),men1.add2());


    // プロトタイプチェーン
    var Animal = function(){};
    Animal.prototype = {
        walk : function(){document.write('tokotoko');}
    }
    var Dog = function(){};
    Dog.prototype = new Animal();
    Dog.prototype.bark = function(){document.write('baubau');}

    var d = new Dog();
    d.walk();
    d.bark();

[/javascript]

[html]

5分でわかる
bxスライダー5つ動かしたらiPhoneでピカピカちらついたんだけど
transform:translate3d(0,0,0)をちらつく箇所に指定したら直った
なぜだ

答えは
tranlate3dを指定するとGPUで処理するようになるからだった

説明
CPUで処理をするアニメーションとGPUで処理をするアニメーションの違い

CPU(GGO)
position:absolut
left:0

こちらは例えるなら画用紙に書いては背景で塗りつぶして書いては移動
ぺらぺら漫画に一枚背景の真っ白な一枚を挟んで移動しているようなもの

GPU(GGO)
transform:transtlate
opacitiyのフェードイン

GPUアクセラーレーションが有効になる=アニメーションのレンダリングをソフトではなくハード(グラフィックチップスが担当になる)

photoshopの背景レイヤーの上にある描画されているレイヤーが移動するようなもの

Android OSが2.3以下はGPUアクセラーレーションが利かない

レンダリング時の負荷によるアニメーションの遅れが一枚真っ白な背景がピカピカの原因

パフォーマンスの違い
css、animationだけで移動
javascriptだけで移動

css、translatetransform
javascriptでtransform

パフォーマンス
ほかのGPUに演算させるプロパティは??

ここで注意
GPUをbodyに指定するとよくないよ
GPUは画像処理にすぐれているのでそのほかの演算がある要素やコンテンツに指定すると結果
パフォーマンス落ちますよ
ブラウザのバージョンによって異なる不要で無駄かもしれないレイヤーを形成しない

・再描画されている箇所に的確に指定

スクロールは??
再描画されているのでは?

GIFアニメーションは?

確かめる方法は?
開発ツールのrectangle

今後のGPUの行方
WebCLでWebデベロッパもGPUやCPUのマルチコアをブラウザ内で有効利用(==並列処理)できるようになる
https://jp.techcrunch.com/2014/03/20/20140319webcl-will-soon-let-web-developers-harness-the-power-of-multi-core-gpus-and-cpus-from-the-browser/

CSS will-changeプロパティについて知っておくべきこと
https://dev.opera.com/articles/ja/css-will-change-property/

transform: translate3d(0, 0, 0);
こうした方法でハードウェア・アクセラレーションを行うと、
合成レイヤーとして知られているものが生成されます。
これは、GPUにアップロードされGPUによって合成されるレイヤーです。
しかし、CSSハックを用いたレイヤー生成は、パフォーマンス・ボトルネックの解消に必ずしも役立ちません。
レイヤーを作らせることでページ表示速度は速くなるかも知れませんが、コストがかかります。
RAMやGPUのメモリ使用量が多くなり(特にモバイル端末では)、
レイヤーをたくさん抱えると悪影響が及びます(特にモバイル端末では)。
ですから、ハックを使うときは慎重に扱わなければなりません。
ハードウェア・アクセラレーションの実行によって本当にページ表示が最適化されるのか、
そしてその操作で新たなパフォーマンス・ボトルネックが起きていないことを確認した上で、
これらのテクニックを使うようにしなければなりません。

transform:transform3dは
cssハックだった!

なぜ3次元の処理を2次元のアニメーションに指定しているのか!!
ブラウザをだましてレイヤー生成を促すCSSハック!

null transoin

まとめ
GPUちゃんと使おうGPU

参考

GPUの可視化
Visualizing WebKit's hardware acceleration

Web制作にGPU処理を取り入れる
https://w3g.jp/blog/studies/web_gpu_adopt

Mobile Safariで2Dアニメーションを実行する時に、本当にtranslate3dを使用すべきなのか検証してみました
https://blog.bluearrowslab.com/smartphone/topicks/663/

</div>

chromeデベロッパーツール
パフォーマンスの調べ方を完全にマスター

will-changeプロパティ
要素に変更を加える前に前もってブラウザに知らせておけるプロパティ
だが
上述したスタックコンテキストや包含ブロックを生じるような場合以外に、will-changeが要素に直接的な影響を与えることはありません。
レクタングルの操作

例えば、clip-pathとopacityプロパティはいずれも、デフォルト値以外の値を指定した時、対象となる要素にスタックコンテキストを生成します。
包含ブロック

パフォーマンス・ヒットとクラッシュ
[/html]

[javascript]

with()
apply call

var gloval;
var re = /(.*)@(.+)\.(.*)/;
var callback = function(){
gloval = arguments;
return arguments[1] + 'at' + arguments[2] + 'dot' + arguments[3];
}
'kennjirmotaitata@yahoo.co.jp'.replace(re,callback);
//"kennjirmotaitataatyahoo.codotjp"

var arry = [];
var csv = 'one, two, three';
var re = csv.replace(/\s/g,'');
arry.push(re);

/<(\S+)(?:\s+.+)?>/
//配列に含めないタグ正規表現

文字列の位置。sliceとsubstringの第二引数に-1を与えた場合

var s = 'moritakenji';
s.slice(0,5);
"morit"
s.slice(0,-1)
"moritakenj"
s.substring(0,-1)
""
s.substring(1,-1)
"m"

substr(0,3)
長さ

s.charAt(0)
位置にある文字を取得

全部とるにはslice(0,-1);

検索位置を返すstring.indexOf();
'moritakenji'.indexOf('o',2)//-1
'moritakenji'.indexOf('o') //1

.コールバック関数

3つある任意の数字を2倍にして配列で返す関数
//失敗
function multi(a,b){
var arr = [];
for(var i in arguments){
var result = arry.push(i *2);
}
return result;
};
var result2 = multi(3,4);
result2

//見本
var i,arr = [];
function muliti(a,b,c){
for(i = 0;i<3;i++){
arr[i] = arguments[i] *2;
}
return arr;
};

function add(a){
return a + 1;
}
var result = muliti(2,3,4);
add(100);

result;
[/javascript]

javascript Ajax-スクロール値によるページ読み込み-

XMLHttpRequestオブジェクトのプロパティ、メソッド、イベント全部調べる

javascript

XMLHttpRequestオブジェクトってどんなメソッドとかプロパティ持っているのかって思ったのでちょっと調べてみた。

利用可能なプロパティ

readyState Number XHR通信の状態を取得
status Number HTTPステータスを取得
statusText String HTTPステータスをテキストで取得
responseText String レスポンスボディの内容をStringで取得
responseXML Document レスポンスボディの内容をDocumentで取得
responseType String レスポンスボディのデータ型を指定する
response * レスポンスボディの内容を任意のデータ型で取得
upload #1 XMLHttpRequestUploadオブジェクトを取得する
timeout Number タイムアウトエラーが発生するまでの時間を設定
withCredentials Boolean Cookieなどの認証情報を送信するか?

1 XMLHttpRequestUpload

利用可能なメソッド

open() 「HTTPメソッド」を指定する「アクセス先URL」を指定する
overrideMimeType() 「MIME Type」のオーバーライドを設定する
send() 「送信データ」を指定する「XHR通信」を開始する
abort() 「XHR通信」を中止する
setRequestHeader() リクエストヘッダを設定する
getResponseHeader() レスポンスヘッダの情報を1つ取得する
getAllResponseHeaders() レスポンスヘッダの情報をまとめて取得

利用可能なイベント

onreadystatechange Event XHR通信の状態が変化するたびに実行される
onloadstart ProgressEvent XHR通信を開始したときに実行される
onprogress ProgressEvent 受信中に繰り返し実行される
onloadend ProgressEvent XHR通信が完了したときに実行される(失敗成功に関係なく)
onload ProgressEvent XHR送信が成功したときに実行される(成功時のみ)
onerror ProgressEvent XHR送信が失敗したときに実行される
onabort ProgressEvent XHR通信を中止すると実行される
ontimeout ProgressEvent タイムアウトエラー発生時に実行される

参照: JavaScript プログラミング講座

こちらはAjaxによるスクロールするとtxtファイルが読み込まれるコード
[javascript]
<script type="text/javascript">
var readingpart = 0;
window.addEventListener('load',
function(event){
var elem = document.getElementById('text');
elem.addEventListener('scroll',scrollText,false);
loadText();
},false);
function loadText(){
var req = new XMLHttpRequest();
req.open('GET','part' + (readingpart + 1) + '.txt');
req.onreadystatechange = function(event){
if(req.readyState == 4){
var text = document.getElementById('text');
if(req.status == 200){
text.innerHTML += req.responseText;
readingpart++;
}
}
};
req.send();
}
function scrollText(event){
var text = event.currentTarget;
var output = document.getElementById('output');
var ss = text.scrollHeight - text.scrollTop;
output.innerHTML =
'H' + text.clientHeight +
' SH:' + text.scrollHeight + ' ST:' + text.scrollTop +
' SS:' + ss;
if(ss <= text.clientHeight){
loadText();
}
};
</script>

[/javascript]

html

[html]
<div id="wrapper">
<h1>テキスト読み込み</h1>
<div id="text"></div>
<div id="output"></div>
</div>
[/html]

JSON

javascript

[javascript]
<script type="text/javascript">
window.addEventListener('load',
function(event){
var elem = document.getElementById('btn_load');
elem.addEventListener('click',loadJSON,false);
},false);
function loadJSON(){
var req = new XMLHttpRequest();
req.open('GET','prod_data.json');
req.onreadystatechange = function(event){
if(req.readyState == 4){
var div = document.getElementById('div_source');
if(req.status == 200){
div.innerHTML = req.responseText;
createTable(req.responseText); }
} else{
div.innerHTML = '読み込みエラー';
}
};
req.send();
};
function createTable(jsontxt){
var prod_data = eval('(' + jsontxt + ')');
var table = document.getElementById('prod_table');
var tbody = document.getElementsByTagName('tbody')[0];
for(var i = 0; i<prod_data.length; i++){
var tr = document.createElement('tr');
var td = document.createElement('td');
td.innerHTML = prod_data[i].name;
tr.appendChild(td);
td = document.createElement('td');
td.innerHTML = prod_data[i].price;
tr.appendChild(td);
tbody.appendChild(tr);
}
}
</script>

[/javascript]

html

[html]
<div id="wrapper">
<h1>テキスト読み込み</h1>
<input type="button" id="btn_load" value="読み込み"></button>
<div id="div_source"></div>
<table id="prod_table">
<tbody>
<thead>
<tr>
<th>製品名</th>
<th>価格</th>
</tr>
</thead>
</tbody>
</table>
</div>
[/html]

javascript-Ajax-

javascript

[javascript]
window.addEventListener('load',
function(event){
var elem = document.getElementById('btn_loadtext');
elem.addEventListener('click',loadText,false);
},false);
function loadText(event){
var req = new XMLHttpRequest();
req.open('GET','aozora.txt');
req.onreadystatechange = function(event){
if(req.readyState == 4){
var text = document.getElementById('text');
if(req.status == 200){
text.innerHTML = req.responseText;
}else{
text.innerHTML = '読み込みエラー';
}
}
};
req.send();
}
[/javascript]

html

[html]
<h1>テキスト読み込み</h1>
<input type="button" id="btn_loadtext" value="読み込み">
<div id="text"></div>

[/html]

[html]

<style> #wrap{ min-width:410px; text-align: center; height: 300px; background: #e2e2e2; } #wrap:before{ display: inline-block; vertical-align: middle; content: ""; height:100%; margin-right: -0.25em; } #inner{ display: inline-block; vertical-align: middle; width: 200px; padding: 10px 15px; } </style> </head> <body> <div id="wrap"> <div id="inner"> <p>ふぁふぁふぁふぁふぁ</p> </div> </div> </body> [/html]

[html]
<p class="p1">&lt;!DOCTYPE <span class="s1">html</span>&gt;</p>
<p class="p1"><span class="s1">&lt;html&gt;</span></p>
<p class="p1">&lt;head&gt;</p>
<p class="p1">&lt;meta <span class="s1">charset</span>="UTF-8"&gt;</p>
<p class="p1">&lt;title&gt;&lt;%=title %&gt;&lt;/title&gt;</p>
<p class="p1">&lt;link type="text.css" <span class="s1">href</span>="style.css" <span class="s1">rel</span>="<span class="s1">stylesheet</span>"&gt;</p>
<p class="p1">&lt;/head&gt;</p>
<p class="p1">&lt;body&gt;</p>
<p class="p1">&lt;h1&gt;&lt;%=title %&gt;&lt;/h1&gt;</p>
<p class="p1">&lt;p&gt;&lt;%=<span class="s1">msg</span> %&gt;</p>
<p class="p1">&lt;/body&gt;</p>
<p class="p1">&lt;/html&gt;</p>

<h3>node.js</h3>
var http = require('http');
var fs = require('fs');
var url = require('url');
var ejs = require('ejs');
var cookie = require('cookie');

var index = fs.readFileSync('./index.ejs','utf8');
var style = fs.readFileSync('./style.css','utf8');
var server = http.createServer();

server.on('request',doRequest);
server.listen(1337);

function doRequest(req,res){
var path = url.parse(req.url);
switch(path.pathname){
case '/' :
var msg = "クッキーはありません";
if(req.headers.cookie != null){
var ck = cookie.parse(req.headers.cookie);
msg = "クッキー:" + ck.lasturl + "," + ck.lasttime;
}
var tmp = ejs.render(index,{
title : 'index Page',
msg : msg
});
res.setHeader('Content-Type','text/html');
res.write(tmp);
res.end();
break;
case '/style.css':
res.setHeader('Content-Type','text/css');
res.write(style);
res.end();
break;
case '/time':
var d = new Date().toDateString();
var ck1 = cookie.serialize('lasttime',d,{
maxAge : 100
});
res.setHeader('Set-Cookie',ck1);
res.setHeader('Content-Type','text/plain');
res.write('SET - COOO_KIEE!');
res.end();
break;
case '/favicon.ico':
break;

default :
res.setHeader('Content-Type','text/plain');
res.setHeader('Set-Cookie',['lasturl=' + path.pathname]);
res.write('SET COOKIE!');
res.end();
break;
}
}
console.log('Server runnning at https://127.0.0.1:1337');

[/html]

Nod.jsを扱うときのEclipseの設定方法とプラグインを使って日本語化(Pleiades)めもめも

①ここのサイトからダウンロード

<

h4>Eclipse IDE for Java EE Developers

<

h4>
https://eclipse.org/downloads/packages/eclipse-ide-java-ee-developers/keplersr2

自分のOSにあったものを右端のところから
bit数はOSの(調べてね)そのものを。
64bitのやつで32bitをダウンロードしたら使えるけど、自分のOSが32なのに64はダメ

わたしはMacなので
ここから
https://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/kepler/SR2/eclipse-jee-kepler-SR2-macosx-cocoa-x86_64.tar.gz

この写真の緑のところ

<

h4>Pleiades - Eclipse プラグイン日本語化プラグイン

<

h4>
https://mergedoc.sourceforge.jp/

写真

気持ち悪い

ここの安定版のほう
ここ

一瞬迷ったけどダウンロード数多い方選んだ

③今ダウンロードしたpleiadesの中の「features」内にある[jp.sourcefore.mergedoc.pleiades]を
コピーしてEclipse内の「features」内にペースト

次にダウンロードしたpleiadesの中の「plugins」内にある[jp.sourcefore.mergedoc.pleiades]を
コピーしてEclipse内の「plugins」内にペースト

eclipse.iniを編集する
※Macの方はeclipse.appをctr+右で「パッケージ内容を表示」でcontentフォルダの中にあるよ

    // var tar = document.getElementById("price")
    // var elem = tar.getElementsByTagName('p');
    // var tagleng = tar.getElementsByTagName('p').length;
    // var str =[],addEleme = '';
    // var re =[],result;
    // for(var i = 0;i<tagleng;i++){
    //   addEleme += elem[i].innerHTML + ',';
    //  result = addEleme.replace(/([0-9]{3}),/g,',$1_');
    //   re = result.split('_');

// re.pop();
//最後の要素を取得して削除
// }
// re;

    // p要素に入っているtextNodeの値を全て取得
    // stringにする
    // 全てのそれに
    // 一番最後から数えて3番目の前にカンマをつける


    //正解
    // function numberFormat(source){
    //  var s = new String(source);
    //  var ret = '';
    //  for (var i = s.length-3; i>0;i-=3){
    //      ret = '.' + s.substr(i,3) + ret;
    //  }
    //  ret = s.substr(0,i+3) + ret;
    //  return ret;
    // }
    // document.write('合計金額は' + numberFormat(2895 * 5) +  'です');円
    // window.alart('保存しました');

var reg = new RegExp('^[0-9]');
reg.test('foo');
false
reg.test('123');
true
var reg = /'^[0-9]'/;
undefined
var reg = /'^[0-9]'/;
function RegExp(){

}
undefined
var reg = /'^[0-9]'/;
reg.constructor;

function RegExp() { [native code] }
var reg = /'^[0-9]'/g;
var reg = /^\s+/;
undefined
reg
/^\s+/
var reg = new RegExp('^\s+');
undefined
var reg = new RegExp('^\s+');
undefined
reg
RegExp {}
var text = 'abc def ghi jkl';
var reg = /(\w+)\s(\w+)/;
reg.exec(text);
["abc def", "abc", "def"]
var reg = /(\w+)\s(\w+)/g;
undefined
reg
/(\w+)\s(\w+)/g
var text = 'abc def ghi jkl';
undefined
reg.exec(text);
["abc def", "abc", "def"]
reg.exec(text);
["ghi jkl", "ghi", "jkl"]
reg.exec(text);
null
var text = 'moritakenji';
var result = text.search(/^kan/g);
result;
-1
var text = 'moritakenji';
var result = text.search(/^moirta/g);
result;
-1
var text = 'moritakenji';
var result = text.search(/^(moirta)/g);
result;
-1
var text = 'abc def ghi jkl';
text.replace(/\s/,',');
"abc,def ghi jkl"
var text = 'abc def ghi jkl';
text.replace(/\s/g,',');
"abc,def,ghi,jkl"
text.replace(/(.)\s/g,',$1');
"ab,cde,fgh,ijkl"
text.replace(/(.)\s/g,function(01m,02m){return ','+ 02m});
Uncaught SyntaxError: Unexpected token ILLEGAL VM50:732
text.replace(/(.)\s/g,function(m0,m1){return ','+ m1});
"ab,cde,fgh,ijkl"
var text = 'abc def ghi jkl';
undefined
text
"abc def ghi jkl"
text.match(/\w/g);
["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l"]
text.match(/(w+)\s/g);
null
text.match(/(w)\s/g);
null
text.match(/(.)\s/g);
["c ", "f ", "i "]
text.match(/(.)\s/g);
["c ", "f ", "i "]
text.match(/([a-z]{,3})\s/g);
null
text.match(/([a-z]{3})\s/g);
["abc ", "def ", "ghi "]
text.match(/([a-z]{1,2})\s/g);
["bc ", "ef ", "hi "]
text.match(/([a-z]{0,1})\s/g);
["c ", "f ", "i "]
text.match(/([a-z]{3})\s/g);
["abc ", "def ", "ghi "]
text.match(/(\w+)\s(\w+)/g);
["abc def", "ghi jkl"]

再帰呼び出し
アクセサプロパティ
with()
apply call

var gloval;
var re = /(.)@(.+).(.)/;
var callback = function(){
gloval = arguments;
return arguments[1] + 'at' + arguments[2] + 'dot' + arguments[3];
}
'kennjirmotaitata@yahoo.co.jp'.replace(re,callback);
//"kennjirmotaitataatyahoo.codotjp"

var arry = [];
var csv = 'one, two, three';
var re = csv.replace(/\s/g,'');
arry.push(re);

/<(\S+)(?:\s+.+)?>/
//配列に含めないタグ正規表現

文字列の位置。sliceとsubstringの第二引数に-1を与えた場合

var s = 'moritakenji';
s.slice(0,5);
"morit"
s.slice(0,-1)
"moritakenj"
s.substring(0,-1)
""
s.substring(1,-1)
"m"

substr(0,3)
長さ

s.charAt(0)
位置にある文字を取得

全部とるにはslice(0,-1);

検索位置を返すstring.indexOf();
'moritakenji'.indexOf('o',2)//-1
'moritakenji'.indexOf('o') //1

.コールバック関数

3つある任意の数字を2倍にして配列で返す関数を実行した後、1を足す関数を実行
//失敗
function multi(a,b){
var arr = [];
for(var i in arguments){
var result = arry.push(i *2);
}
return result;
};
var result2 = multi(3,4);
result2

//見本
var i,arr = [];
function muliti(a,b,c){
for(i = 0;i<3;i++){
arr[i] = arguments[i] *2;
}
return arr;
};
function add(a){
return a + 1;
}
var my = [];
my = muliti(10,30,40);

for(var i = 0;i<3;i++){my[i] = add(my[i])};

ループをへらすことで実行コストを抑える。
1つのコードでやる。
コールバック関数を受け取るようにして繰り返しごとに関数を呼び出す
var my = [];
function muliti(a,b,c,callback){
var i,arr = [];
for(i= 0;i<3;i++){
arr[i] = callback(arguments[i] * 2);
}
return arr;
}
function add(a){
return a + 1;

}
my = muliti(2,3,5,add);

add()の代わりに無名関数を使うとグローバル関数を減らせることができる
var my = [];
function muliti(a,b,c,callback){
var i,arr =[];
for(i=0;i<3;i++){
arr[i] = callback(arguments[i] *2);
}
return arr;
}
my = muliti(2,3,5,function(a){return a + 1})

1

独自オブジェクトのコンストラクタ
function Product(name,price){
    this.name = name;
    this.price = price;
}
var prod_data = [];
prod_data.push(new Product('リラックスチェア','4000'));//{name:'リラックスチェア',price:'4000'}
prod_data.push(new Product('リラックスデスク','12000'));//{name:'リラックスデスク',price:'12000'}
prod_data.push(new Product('ブックスタンド','800'));//{name:'ブックスタンド',price:'800'}
window.addEventListener('load',function(event){
    createTable();

},false);
//表作成関数
function createTable(){//HTMLの生成
    var table = document.getElementById('prod_table');
    var tbody = document.getElementsByTagName('tbody')[0];
    for(var i = 0;i<prod_data.length;i++){
        if(!(prod_data[i] instanceof Product)){
            continue;
        }
        var tr = document.createElement('tr');
        var td = document.createElement('td');
        td.innerHTML= prod_data[i].name;
        tr.appendChild(td);
        td = document.createElement('td');
        td.innerHTML = prod_data[i].price;
        tr.appendChild(td);
        tbody.appendChild(tr);
    }
}

2
//他の関数を作成する場合

//独自オブジェクトのコンストラクタ
function Product(name,price){
    this.name = name;
    this.price = price;
    //コンストラクタに定義
    this.calcPrice1 = function(amount){
        return this.price * amount;
    }
}
//プロトタイプで共有
Product.prototype.calcPrice2= function(amount){
    return this.price * amount;
}
var prod_data = [];
prod_data.push(new Product('リラックスチェア','4000'));
prod_data.push(new Product('リラックスデスク','12000'));
prod_data.push(new Product('ブックスタンド','800'));

window.addEventListener('load',function(event){
    createTable();

},false);
function TableTool(){}//静的メソッドを作成
TableTool.createTdStr = function(value){
    var str = '';
    for(var i= 0;i<value.length;i++){
        str += '<td>' + value[i] + '</td>';
    }
    return str;
}
//表作成関数
function createTable(){
    var table = document.getElementById('prod_table');
    var tbody = document.getElementsByTagName('tbody')[0];
    for(var i = 0; i < prod_data.length; i++){
        var tr = document.createElement('tr');
        tr.innerHTML = TableTool.createTdStr(
            [prod_data[i].name,
            prod_data[i].price,
            prod_data[i].calcPrice2(10),
            prod_data[i].calcPrice2(20),
            prod_data[i].calcPrice2(30)
            ]
        );
        tbody.appendChild(tr);
        }
    }

3

// オブジェクトの継承
//独自オブジェクトのコンストラクタ
function Product(name,price){
    this.name = name;
    this.price = price;
}
Product.prototype.calcPrice = function(amount){
    return this.price * amount;
}
function HardProduct(name,price){//継承元と同じプロパティを定義する必要がある。そうしないとprototypeで継承元をたどってしまうから
    this.name = name;
    this.price = price;
    this.zaiko = 0;
}
HardProduct.prototype = new Product();//継承したいオブジェクト(継承元)のインスタンスを代入する

function SoftProduct(name,price){
    this.name = name;
    this.price = price;
}
SoftProduct.prototype = new Product();//継承はprototypeに対しての代入になる。これ逆にするとprototypeに対して追加していたメソッドが消えてしまう
SoftProduct.prototype.calcPrice = function(){
    return '---';
}
var prod_data = [];
prod_data.push(new HardProduct('リラックスチェア','4000'));
prod_data.push(new HardProduct('リラックスデスク','12000'));
prod_data.push(new HardProduct('ブックスタンド','800'));
prod_data.push(new SoftProduct('設置サービス','2800'));
prod_data.push(new SoftProduct('1年保証','5800'));
window.addEventListener('load',function(event){
    createTable();
},false);

function TableTool(){}//静的メソッドを作成
TableTool.createTdStr = function(value){
    var str = '';
    for(var i= 0;i<value.length;i++){
        str += '<td>' + value[i] + '</td>';
    }
    return str;
}
//表作成関数
function createTable(){
    var table = document.getElementById('prod_table');
    var tbody = document.getElementsByTagName('tbody')[0];
    for(var i = 0; i < prod_data.length; i++){
        if(!(prod_data[i] instanceof Product)){
            continue;
        }
        var tr = document.createElement('tr');
        tr.innerHTML = TableTool.createTdStr(
            [
            prod_data[i].name,
            prod_data[i].price,
            prod_data[i].calcPrice(10),
            prod_data[i].calcPrice(20),
            prod_data[i].calcPrice(30)
            ]
        );
        tbody.appendChild(tr);
        }
    }

<style> 
table{border:solid 1px orange;border-spacing:0px;}
th,td{border:solid 1px orange;padding: 4px}
</style>


新製品価格表

</table>



-->

animate()とqueue()とstop()の備忘録まとめ

animate()

  • animateの第二引数にオブジェクトをわたしqueueプロパティでfalseにすると並列して動く
  • queue()に続くanimateはnext()で実行しなければいけない

dequeue()

  • 引数にnextを渡し関数内でnext()ことで次に設定されているqueueを実行できる
  • 第一引数にqueue名、dequequeの引数にして実行
  • 配列に入れて関数を実行

stop()

  • 第一引数trueは今のアニメーションを最後の状態にする。第二引数trueはキューの終了状態にする

$(function(){
//1
// $('#square').animate({width:'+=50px',height:'+=50px'}).delay(1000).animate({fontSize:'+=25px'});

//2
// $('#square').animate({width:'+=50px',height:'+=50px'}).animate({fontSize:'+=25px'},{queue:false});

//3
// $('#square').animate({height:'+=100px'});
// $('#square').queue(function(){
// $(this).animate({width:'+=100px'});
// });
// $('#square').dequeue();

//4
// $('#square').animate({
// width:'+=50px'
// });
// $('#square').queue(function(){
// $(this).animate({
// height:'+=50px'
// });
// });
// setTimeout(function(){
// $('#square').dequeue();
// },3000);

//5
// $('#square').queue(function(next){
// $(this).animate({height:'+=50px'});
// next();
// }).queue(function(){
// $(this).animate({height:'+=100px'});
// });
// $('#square').dequeue();

// 6
// $('#square').queue(function(next){
// $(this).animate({width:'+=100px'});
// next();
// });
// $('#square').animate({height:'+=50px'});

//7
// $('#square').queue([
// function(){$(this).animate({height:'+=100px'});},
// function(){$(this).animate({width:'+=100px'});}
// ]);
// $('#square').dequeue().dequeue();

//8
// $('#square').queue('myq',function(next){
// $(this).animate({height:'+=50px'});
// next();
// }).queue('myq',function(){
// $(this).animate({width:'+=100px'});
// });
// $('#square').dequeue('myq');
// $('#square').clearQueue('myq');

//9
// var speed = 1000;
// $('#square')
// .animate({height:'+=150px'},speed)
// .delay(speed/2)
// .animate({width:'+=150px'},speed);
// setTimeout(function(){
// $('#square').stop();
// },speed*2);

//10
// var speed = 3000;
// $('#square')
// .animate({width:'+=130px'},speed)
// .animate({height:'+=130px'},speed);
// setTimeout(function(){
// $('#square').stop(false,true);
// },speed/3);

//11
var speed = 3000;
$('#square')
.animate({width:'+=130px'},speed)
.animate({height:'+=130px'},speed);
setTimeout(function(){
$('#square').stop(true);
},speed/2);
});

「武骨日記」TOPページへ
全記事リンク集

JQueryのanimate()、queue()、dequeue()、のリマインド

queueをfalseにすることでanimateと同時に実行

// 1 $(function(){
// $('#yellow').animate({width:'+=150px',height:'+=150px'},5000).animate({fontSize:'+=25px'},{queue:false});
// });

queueに設定した後、dequeueで実行
// 2 $(function(){
// $('#yellow').animate({height:'+=100px'});
// $('#yellow').queue(function(){
// $(this).animate({width:'+=100px'});
// });
// $('#yellow').dequeue();

// }); 続きを読む

こちらはTOPページではありません。

TOPページへ

こちらTOPへ行かれてブックマークして頂くと一層色んな記事が頻繁に更新され、ご覧頂けます。
お手数ですが宜しくお願い致します。。

いつもこの画面でご覧頂いてた方へ
半年前からTOPの方では色々な記事がUPしていました。
すみません。このページで行き止まりだったみたいです。。
どうりで他の記事見られてないなぁと。。

いろんな記事が上がっているのでよかったら見てやってください

もりたけんじ

// var str1 = 'にわにはにわにわとりがいる';
// document.writeln(str1.indexOf('にわ'));//0(先頭から検索)
// document.writeln(str1.lastIndexOf('にわ'));//6(末尾から検索)
// document.writeln(str1.indexOf('にわ',3));//4文字目から右方向に検索
// document.writeln(str1.lastIndexOf('わ',5));//4(6文字目から左方向検索)
// document.writeln(str1.indexOf('ガーデン'));//-1(不一致)

// var str2 = 'Wingsプロジェクト';
// document.writeln(str2.charAt(4));//sを抽出
// document.writeln(str2.slice(5,8);//プロジ(6~8文字目を抽出)
// document.writeln(str2.substring(5,8));//プロジ(6~8文字目を抽出)
// document.writeln(str2.substr(5,3));//6番目から3文字を抽出
// document.writeln(str2.split('s'));//Wing,プロジェクト
// document.writeln(str1.split('わ',3));//に,にはに,に(3つに分割)

// document.writeln('トップ',anchor('top'));//トップ
// document.writeln(str2.link('https://www.wings.mns'));
// document.writeln('10',sub());//10下付き文字
// document.writeln('10',sup());//10上付き文字

// document.writeln(str2.concat('有限会社'));//Wingsプロジェクト有限会社
// document.writeln(str2.length);//11(日本語も一文字と換算)

// //substring,sliceとsubstrの違い。前者は番目を返す。後者は番目から文字数を返す
// // substringとsliceの違い
// var str = 'WINGSプロジェクト';
// document.writeln(str.substring(8.5));//プロジ(6~8文字目を抽出)引数startと引数endをend+1、start-1文字目までを抽出
// document.writeln(str.slice(8.5));//空文字。入れ替えはしない

// var str = 'WINDOWプロジェクト';
// document.writeln(str.substring(5,-2));//WINDO(1~5番目を抽出)substringは-2を0とみなしend、startを交換するから0から5番目までを抽出
// document.writeln(str.slice(5,-2));//(5,9)になる。負の数は後方の文字数とみなす。-2は後方から3文字目、つまり9文字目slice(5,-2)はstr.slice(5,9)と同じ動作をする

// Arrayオブジェクト

// var ary1 = ['Sato','Takae','Osada','Hio','Saitoh'];
// var ary2 = ['Yabuki','Aoki','Moriyama','Yamada'];

// document.writeln(ary1.concat(ary2));
// //Sato,Takae,Osada,Hio,Saitoh,Yabuki,Aoki,Moriyama,Yamada 配列通しで繋げる
// document.writeln(ary1.join('/'));
// //Sato/Takae/Osada/Hio/Saitoh 第一引数で繋げる
// document.writeln(ary1.slice(1));//Takae,Osada,Hio,Saitoh Satoを削除
// document.writeln(ary1.slice(1,2));//Takae
// document.writeln(ary1.splice(1,2,'kakeya','Yamaguchi'));
// //Takae,Osada(置き換え対象の要素を取得)
// document.writeln(ary1);
// //Sato,kakeya,Yamaguchi,Hio,Saitoh(置き換え後の配列)

// document.writeln(ary1.pop());//Saitoh(削除した要素)

製品名 価格 10個 20個 30個
2024年3月
 123
45678910
11121314151617
18192021222324
25262728293031