javascriptのMath JSON
3866 ワード
Mathオブジェクト
<script type="text/javascript">
var max = Math.max(3, 54, 32, 16);
alert(max); //54
var min = Math.min(3, 54, 32, 16);
alert(min); //3
</script>
<script type="text/javascript">
function selectFrom(lowerValue, upperValue) {
var choices = upperValue - lowerValue + 1;
return Math.floor(Math.random() * choices + lowerValue);
}
var num = selectFrom(2, 10);
alert(num); //number between 2 and 10 (inclusive)
var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
var color = colors[selectFrom(0, colors.length-1)];
alert(color); //any of the strings in the array
</script>
JSONオブジェクト <script type="text/javascript">
var book = {
title: "Professional JavaScript",
authors: [
"Nicholas C. Zakas"
],
edition: 3,
year: 2011
};
var jsonText = JSON.stringify(book, ["title", "edition"]);
alert(jsonText);
</script>
//
<script type="text/javascript">
var book = {
title: "Professional JavaScript",
authors: [
"Nicholas C. Zakas"
],
edition: 3,
year: 2011
};
var jsonText = JSON.stringify(book, function(key, value){
switch(key){
case "authors":
return value.join(",")
case "year":
return 5000;
case "edition":
return undefined;
default:
return value;
}
});
alert(jsonText);
</script>
toJSON()方法 <script type="text/javascript">
var book = {
"title": "Professional JavaScript",
"authors": [
"Nicholas C. Zakas"
],
edition: 3,
year: 2011,
toJSON: function(){
return this.title;
}
};
var jsonText = JSON.stringify(book);
alert(jsonText);
</script>
解析オプション <script type="text/javascript">
var book = {
"title": "Professional JavaScript",
"authors": [
"Nicholas C. Zakas"
],
edition: 3,
year: 2011,
releaseDate: new Date(2011, 11, 1)
};
var jsonText = JSON.stringify(book);
alert(jsonText);
var bookCopy = JSON.parse(jsonText, function(key, value){
if (key == "releaseDate"){
return undefined;
} else {
return value;
}
});
alert("releaseDate" in bookCopy);
</script>