純粋JavaScript論理まとめ
4525 ワード
1.二次元配列は一次元配列に変わります.
function double_to_one() {
collection = [1,[2],[3,4]]
var array = [];
for(var i = 0;i< collection.length;i++){
var new_array = collection[i];
if( new_array instanceof Array == true ){
for(var j = 0;j< new_array.length;j++){
array.push(new_array[j]);
}
}
else{
array.push(new_array);
}
}
return array;
}
// array = [1,2,3,4]
2.配列の並べ替え
var rank_asc = function(){
var collection = [2,4,1,6,5,3]
var array = collection.sort();
array = array.reverse();
return array;
};
//array = [6,5,4,3,2,1]
var rank_asc = function(collection){
var collection = [1,4,2,6,3,5]
var array = collection.sort();
return array;
};
// array = [1,2,3,4,5,6]
3、与えられた配列は、与えられた結果に従って出力されます.function count_same_elements_3(collection){
var collection = var collection = [
"a", "a", "a",
"e", "e", "e", "e", "e", "e", "e",
"h", "h", "h", "h", "h", "h", "h[3]", "h", "h",
"t", "t-2", "t", "t", "t", "t", "t", "t", "t[10]",
"f", "f", "f", "f", "f", "f", "f", "f", "f",
"c:8",
"g", "g", "g", "g", "g", "g", "g",
"b", "b", "b", "b", "b", "b",
"d-5"
];
var result = [];
var new_array = [];
var length = collection.length;
for(var i = 0;i < length; i++){
for(var j = i+1; j < length; j++){
if(collection[i] === collection[j]){
j = ++i;
}
}
new_array.push(collection[i]);
} //
for(var i=0;i<new_array.length;i++){
var number = 0;
var temp = new_array[i];
var position = temp.indexOf('-');// '-'
var positions = temp.indexOf(':');
var positionss = temp.indexOf('[');
if(position != -1 ){ //-1 (‘-’)
number = parseFloat(temp.substr(position + 1));//
temp = temp.substr(0,position);
}
else if(positions != -1){
number = parseFloat(temp.substr(positions + 1));
temp = temp.substr(0,positions);
}
else if(positionss != -1){
number = parseFloat(temp.substr(positionss + 1));
temp = temp.substr(0,positionss);
}
else{
for(var j = 0; j < collection.length; j++){
if(collection[j] == temp){
number++;
}
}
}
var k = {name: temp, summary: number};
if(result.length == 0){
result.push(k);
}
else {
for (var n = 0, len = result.length; n < len; n++) {
if (k.name == result[n].name) {
result[n].summary += k.summary;
}
else if(k.name !== result[n].name && n == len -1){ //
result.push(k);
}
}
}
number = 0;
}
return result;
}
// result = [
{name: "a", summary: 3},
{name: "e", summary: 7},
{name: "h", summary: 11},
{name: "t", summary: 19},
{name: "f", summary: 9},
{name: "c", summary: 8},
{name: "g", summary: 7},
{name: "b", summary: 6},
{name: "d", summary: 5}
]
4.小数点以下を揃える1. ,
parseInt(5/2) // 2
parseInt(7/4) //1
2. , 1
Math.cell(5/3) // 2
Math.ceil(5/2) //3
3, .
Math.round(5/2) //3
4,
Math.floor(5/3) //1
Math.floor(5/2) //2